<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <div class="page-container-grouped-styles">
            <funnelHeader cmsWidgetName="FunnelHeaderWidget" />
            <vehicleBanner
                cmsWidgetName="VehicleBannerWidget"
                :displayGenericVehicleImage="false" />
            <funnelSubHeader cmsWidgetName="FunnelSubHeaderWidget" />
            <div class="fade-on-route-transition sub-container make-tall">
                <alert
                    ref="vehicleChangeAlert"
                    v-if="shouldDisplayVehicleChangeAlert"
                    class="mt-5 mb-0"
                    cmsWidgetName="VehicleChangeAlert"
                    alertClass="alert-warning"
                    :isDismissible="false" />
                <damageLocationQuestion
                    ref="damageLocation"
                    cmsWidgetName="DamageLocationQuestion"
                    v-model="selectedDamageLocations"
                    groupName="DamageLocationQuestion" />
                <windshieldOptions
                    ref="windshieldOptions"
                    v-model="selectedWindshieldOptions"
                    :hasRepairReplaceConflict="hasRepairReplaceConflict"
                    :hasSplitSingleConflict="hasSplitSingleConflict"
                    :selectedDamageLocations="selectedDamageLocations" />
                <alert
                    v-if="hasRepairReplaceConflict"
                    class="my-5"
                    cmsWidgetName="HasReplacementConflict"
                    alertClass="alert-danger"
                    :isDismissible="false" />
                <sideDoorOptions
                    ref="sideDoorOptions"
                    cmsWidgetName="SideDoorSideQuestion"
                    groupName="SideDoorSideQuestion"
                    v-model="sideDoorOptionsData"
                    v-show="!hasRepairReplaceConflict"
                    :selectedDamageLocations="selectedDamageLocations" />
                <replaceOptionsQuestion
                    ref="backGlassOptions"
                    cmsWidgetName="RearReplaceOptionsQuestion"
                    :isAvailable="isRearWindowDamageLocation && !hasRepairReplaceConflict"
                    v-model="selectedRearReplaceOptions"
                    groupName="BackGlassReplaceOptionsQuestion"
                    validationRules="replace-options-required" />
                <funnel-footer
                    cmsWidgetName="FunnelFooterWidget"
                    :isForwardActionDisabled="!meta.valid"
                    :isBackButtonHidden="shouldHideBackButton"
                    @back-clicked="backButtonAction"
                    @ForwardClicked="forwardButtonAction" />
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import funnelHeader from "@/fmg-components/funnel-header/funnel-header";
import funnelFooter from "@/fmg-components/funnel-footer/funnel-footer";
import vehicleBanner from "@/fmg-components/vehicle-banner/vehicle-banner";
import funnelSubHeader from "@/fmg-components/funnel-sub-header/funnel-sub-header";
import sideDoorOptions from "@/layouts/vehicle-damage/side-door-options/side-door-options";
import damageLocationQuestion from "@/layouts/vehicle-damage/damage-location-question/damage-location-question";
import windshieldOptions from "@/layouts/vehicle-damage/windshield-options/windshield-options";
import replaceOptionsQuestion from "@/layouts/vehicle-damage/replace-options-question/replace-options-question";
import alert from "@/ux-components/alert/alert";

// Supporting files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import { storeActions } from "@/constants/store-actions";
import { Form, defineRule } from "vee-validate";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import { damageLocationsCms } from "@/constants/damage-locations-cms.js";
import { damageLocationsSelected } from "@/constants/damage-locations-selected.js";
import { getFunnelCookie } from "@/helpers/heritage-integration/cookie-helper";

import store from "@/store";
import baseMixin from "@/mixins/base-mixin";
// DEFINE VALIDATION RULES
defineRule("replace-options-required", required(errorMessages.REPLACE_OPTIONS_REQUIRED));

export default {
    name: "vehicle-damage",
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);

        const damageOptionsPromise = baseMixin.methods.dispatchStoreAction(
            storeActions.GET_DAMAGE_OPTIONS,
            { carId: store.getters.vehicle.carId }
        );

        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: "cmsContent",
                promise: cmsContentPromise,
            },
            {
                resultKey: "damageOptions",
                promise: damageOptionsPromise,
            },
        ];

        const resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.$refs.damageLocation.initializeComponent(resultMap.damageOptions);
            vm.$refs.sideDoorOptions.initializeComponent(
                resultMap.damageOptions.driverSideOptions.availableReplacementOptions,
                resultMap.damageOptions.passengerSideOptions.availableReplacementOptions
            );
            vm.$refs.windshieldOptions.initializeComponent(
                resultMap.damageOptions.windshieldOptions.availableReplacementOptions
            );
            vm.$refs.backGlassOptions.initializeComponent(
                resultMap.damageOptions.backGlassOptions.availableReplacementOptions
            );
        });
    },
    data() {
        return {
            selectedDamageLocations: this.getDamageLocationsFromStore(),
            sideDoorOptionsData: {
                selectedDoorSides: this.getDoorSidesFromStore(),
                selectedDriverSideReplaceOptions: this.getDriverSideReplaceOptionsFromStore(),
                selectedPassengerSideReplaceOptions: this.getPassengerSideReplaceOptionsFromStore(),
            },
            selectedWindshieldOptions: this.getWindshieldOptionsFromStore(),
            selectedRearReplaceOptions: this.getRearReplaceOptionsFromStore(),
        };
    },
    mounted() {
        this.attachCustomEvents();
    },
    methods: {
        arePagePrerequisitesValid() {
            if (store.getters.vehicle.carId) {
                return true;
            }
            return false;
        },

        attachCustomEvents() {
            if (this.$store.getters.vehicle.imageVifNumber) {
                this.pushEventToGA(
                    this.GaCategories.EVOX,
                    `${this.GaActions.VIF}_${this.$store.getters.vehicle.imageVifNumber}`,
                    this.$store.getters.vehicle.carId,
                    true
                );
            }
        },

        backButtonAction() {
            // route to move backwards
            this.$router.navigateWithoutSaving(this.navigationScenarios.CLICKED_BACK, this.$route);
        },

        getDamageLocationsFromStore() {
            var glassSelections = [];

            if (
                store.getters.damage.glassToReplace?.some((glass) => {
                    return glass.glassLocation === damageLocationsSelected.WINDSHIELD;
                }) ||
                store.getters.damage.isRepair
            ) {
                glassSelections.push(damageLocationsSelected.WINDSHIELD);
            }
            if (
                store.getters.damage.glassToReplace?.some((glass) => {
                    return (
                        glass.glassLocation === damageLocationsSelected.DRIVER ||
                        glass.glassLocation === damageLocationsSelected.PASSENGER
                    );
                })
            ) {
                glassSelections.push(damageLocationsSelected.SIDEDOOR);
            }

            if (
                store.getters.damage.glassToReplace?.some((glass) => {
                    return glass.glassLocation === damageLocationsSelected.REAR;
                })
            ) {
                glassSelections.push(damageLocationsSelected.REARWINDOW);
            }

            return glassSelections;
        },

        getWindshieldOptionsFromStore() {
            var windShieldOptions = {
                selectedWindshieldDamageType: "",
                selectedWindshieldChipCount: null,
                selectedWindshieldReplaceOptions: [],
            };

            if (store.getters.damage.isRepair === undefined) return windshieldOptions;

            if (store.getters.damage.isRepair) {
                windShieldOptions.selectedWindshieldDamageType = damageLocationsSelected.REPAIR;
                windShieldOptions.selectedWindshieldChipCount = store.getters.damage.numberOfChips;
            } else {
                if (
                    store.getters.damage.glassToReplace?.some((glass) => {
                        return (
                            glass.glassLocation === damageLocationsSelected.WINDSHIELD &&
                            glass.glassName === damageLocationsSelected.SINGLE
                        );
                    })
                ) {
                    windShieldOptions.selectedWindshieldDamageType =
                        damageLocationsSelected.REPLACE;
                    windShieldOptions.selectedWindshieldReplaceOptions.push(
                        damageLocationsSelected.SINGLE
                    );
                }

                if (
                    store.getters.damage.glassToReplace?.some((glass) => {
                        return (
                            glass.glassLocation === damageLocationsSelected.WINDSHIELD &&
                            glass.glassName === damageLocationsSelected.DRIVER
                        );
                    })
                ) {
                    windShieldOptions.selectedWindshieldDamageType =
                        damageLocationsSelected.REPLACE;
                    windShieldOptions.selectedWindshieldReplaceOptions.push(
                        damageLocationsSelected.DRIVER
                    );
                }

                if (
                    store.getters.damage.glassToReplace?.some((glass) => {
                        return (
                            glass.glassLocation === damageLocationsSelected.WINDSHIELD &&
                            glass.glassName === damageLocationsSelected.PASSENGER
                        );
                    })
                ) {
                    windShieldOptions.selectedWindshieldDamageType =
                        damageLocationsSelected.REPLACE;
                    windShieldOptions.selectedWindshieldReplaceOptions.push(
                        damageLocationsSelected.PASSENGER
                    );
                }
            }

            return windShieldOptions;
        },

        getDoorSidesFromStore() {
            var doorSides = [];
            if (
                store.getters.damage.glassToReplace?.some((glass) => {
                    return glass.glassLocation === damageLocationsSelected.DRIVER;
                })
            ) {
                doorSides.push(damageLocationsSelected.DRIVERSIDE);
            }

            if (
                store.getters.damage.glassToReplace?.some((glass) => {
                    return glass.glassLocation === damageLocationsSelected.PASSENGER;
                })
            ) {
                doorSides.push(damageLocationsSelected.PASSENGERSIDE);
            }

            return doorSides;
        },

        getDriverSideReplaceOptionsFromStore() {
            var driverSideReplaceOptions = [];

            store.getters.damage.glassToReplace?.forEach((glass) => {
                if (glass.glassLocation === damageLocationsSelected.DRIVER) {
                    driverSideReplaceOptions.push(glass.glassName);
                }
            });

            return driverSideReplaceOptions;
        },

        getPassengerSideReplaceOptionsFromStore() {
            var passengerSideReplaceOptions = [];

            store.getters.damage.glassToReplace?.forEach((glass) => {
                if (glass.glassLocation === damageLocationsSelected.PASSENGER) {
                    passengerSideReplaceOptions.push(glass.glassName);
                }
            });

            return passengerSideReplaceOptions;
        },

        getRearReplaceOptionsFromStore() {
            var rearReplaceOptions = store.getters.damage.glassToReplace?.filter(
                (glass) => glass.glassLocation === damageLocationsSelected.REAR
            )[0]?.glassName;

            return rearReplaceOptions;
        },

        async forwardButtonAction() {
            await this.dispatchStoreAction(
                this.storeActions.SAVE_VEHICLE_DAMAGE,
                {
                    isWindshieldRepair: this.isWindshieldRepair,
                    selectedGlassToReplace: this.selectedGlassToReplace(),
                    selectedWindshieldChipCount:
                        this.selectedWindshieldOptions.selectedWindshieldChipCount,
                },
                false
            );

            if (this.isWindshieldRepair) {
                const supportingItems = await this.dispatchStoreAction(
                    storeActions.GET_SUPPORTING_ITEMS
                );
                this.dispatchStoreAction(
                    this.storeActions.SAVE_SUPPORTING_ITEMS,
                    supportingItems.data,
                    false
                );
            }

            return this.navigateForward();
        },

        navigateForward() {
            const payment = this.$store.getters.payment;

            const vehicleChangedDuringPolicyLookupInHeritage =
                payment.isInsurance &&
                payment.insuranceCoverage.coverageStatus &&
                payment.insuranceCoverage.coverageStatus !== "";
            if (vehicleChangedDuringPolicyLookupInHeritage) {
                if (store.getters.damage.isRepair) {
                    this.$router.navigateWithSaving(
                        this.navigationScenarios.CLICKED_FORWARD_WITH_REPAIR_AND_VERIFIED_INSURANCE,
                        this.$route
                    );
                } else {
                    this.$router.navigateWithSaving(
                        this.navigationScenarios
                            .CLICKED_FORWARD_WITH_REPLACE_AND_VERIFIED_INSURANCE,
                        this.$route
                    );
                }
            }
            // If vin already exists, navigate directly to vin-lookup
            else if (store.getters.vehicle.vin) {
                this.$router.navigateWithSaving(
                    this.navigationScenarios.CLICKED_FORWARD_WITH_VIN,
                    this.$route
                );
            } else {
                this.$router.navigateWithSaving(
                    this.navigationScenarios.CLICKED_FORWARD_WITHOUT_VIN,
                    this.$route
                );
            }
        },

        selectedGlassToReplace() {
            const selectedGlassToReplace = [];
            if (this.isWindshieldDamageLocation && !this.isWindshieldRepair) {
                this.selectedWindshieldOptions.selectedWindshieldReplaceOptions.forEach(
                    (wsItem) => {
                        selectedGlassToReplace.push({
                            glassLocation: damageLocationsSelected.WINDSHIELD,
                            glassName: wsItem,
                        });
                    }
                );
            }

            if (this.isDriverSideReplace) {
                this.sideDoorOptionsData.selectedDriverSideReplaceOptions.forEach((driverItem) => {
                    selectedGlassToReplace.push({
                        glassLocation: damageLocationsSelected.DRIVER,
                        glassName: driverItem,
                    });
                });
            }

            if (this.isPassengerSideReplace) {
                this.sideDoorOptionsData.selectedPassengerSideReplaceOptions.forEach(
                    (passengerItem) => {
                        selectedGlassToReplace.push({
                            glassLocation: damageLocationsSelected.PASSENGER,
                            glassName: passengerItem,
                        });
                    }
                );
            }

            if (this.isRearWindowDamageLocation) {
                selectedGlassToReplace.push({
                    glassLocation: damageLocationsSelected.REAR,
                    glassName: this.selectedRearReplaceOptions,
                });
            }

            return selectedGlassToReplace;
        },
    },
    computed: {
        isWindshieldDamageLocation() {
            return this.selectedDamageLocations.some((selectedDamages) => {
                return selectedDamages.toUpperCase() === damageLocationsCms.WINDSHIELD;
            });
        },
        isSideDoorDamageLocation() {
            return this.selectedDamageLocations.some((selectedDamages) => {
                return selectedDamages.toUpperCase() === damageLocationsCms.SIDEDOOR;
            });
        },
        isRearWindowDamageLocation() {
            return this.selectedDamageLocations.some((selectedDamages) => {
                return selectedDamages.toUpperCase() === damageLocationsCms.REARWINDOW;
            });
        },
        isWindshieldRepair() {
            return (
                this.isWindshieldDamageLocation &&
                this.selectedWindshieldOptions.selectedWindshieldDamageType ===
                    damageLocationsSelected.REPAIR
            );
        },
        isDriverSideReplace() {
            if (!this.isSideDoorDamageLocation) return false;

            return this.sideDoorOptionsData.selectedDoorSides.some((selectedDriverSide) => {
                return selectedDriverSide.toUpperCase() === damageLocationsCms.DRIVERSIDE;
            });
        },
        isPassengerSideReplace() {
            if (!this.isSideDoorDamageLocation) return false;

            return this.sideDoorOptionsData.selectedDoorSides.some((selectedPassengerSide) => {
                return selectedPassengerSide.toUpperCase() === damageLocationsCms.PASSENGERSIDE;
            });
        },
        hasRepairReplaceConflict() {
            return (
                this.isWindshieldDamageLocation &&
                this.selectedDamageLocations.length > 1 &&
                this.isWindshieldRepair
            );
        },
        hasSplitSingleConflict() {
            if (
                !this.selectedDamageLocations?.includes("Windshield") ||
                this.selectedWindshieldOptions.selectedWindshieldDamageType ===
                    damageLocationsSelected.REPAIR ||
                !this.selectedWindshieldOptions.selectedWindshieldReplaceOptions
            )
                return false;

            return (
                this.selectedWindshieldOptions.selectedWindshieldReplaceOptions?.some(
                    (selectedSingleWindshield) => {
                        return (
                            selectedSingleWindshield.toUpperCase() ===
                            damageLocationsSelected.SINGLE.toUpperCase()
                        );
                    }
                ) &&
                (this.selectedWindshieldOptions.selectedWindshieldReplaceOptions?.some(
                    (selectedDriverWindshield) => {
                        return (
                            selectedDriverWindshield.toUpperCase() ===
                            damageLocationsSelected.DRIVER.toUpperCase()
                        );
                    }
                ) ||
                    this.selectedWindshieldOptions.selectedWindshieldReplaceOptions?.some(
                        (selectedPassengerWindshield) => {
                            return (
                                selectedPassengerWindshield.toUpperCase() ===
                                damageLocationsSelected.PASSENGER.toUpperCase()
                            );
                        }
                    ))
            );
        },
        shouldDisplayVehicleChangeAlert() {
            return this.$route.params[this.routerParams.DISPLAY_VEHICLE_CHANGE_ALERT];
        },
        shouldHideBackButton() {
            return (
                this.$store.getters.payment.insuranceCoverage.isVerified ||
                getFunnelCookie()?.HasDelayedClaimRegistration
            );
        },
    },

    components: {
        funnelHeader,
        funnelFooter,
        vehicleBanner,
        funnelSubHeader,
        sideDoorOptions,
        damageLocationQuestion,
        windshieldOptions,
        replaceOptionsQuestion,
        Form,
        alert,
    },
};
</script>
