<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <div class="page-container-grouped-styles">
            <siteHeader cmsWidgetName="SiteHeaderWidget" />
            <vehicleBanner
                cmsWidgetName="VehicleBannerWidget"
                :displayGenericVehicleImage="false" />
            <siteSubHeader cmsWidgetName="SiteSubHeaderWidget" />
            <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" />
                <site-footer
                    cmsWidgetName="SiteFooterWidget"
                    :isForwardActionDisabled="!meta.valid"
                    @back-clicked="backButtonAction"
                    @ForwardClicked="forwardButtonAction" />
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import siteHeader from "@/common-components/site-header/site-header";
import siteFooter from "@/common-components/site-footer/site-footer";
import vehicleBanner from "@/common-components/vehicle-banner/vehicle-banner";
import siteSubHeader from "@/common-components/site-sub-header/site-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 { 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 { useMainStore } from '@/store';

// 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.issPage);
        const damageOptionsPromise = useMainStore().getDamageOptions(useMainStore().order.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(),
        };
    },
    methods: {
        arePagePrerequisitesValid() {
            if (this.mainStore.order.vehicle.carId) {
                return true;
            }
            return false;
        },

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

        getDamageLocationsFromStore() {
            var glassSelections = [];

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

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

            return glassSelections;
        },

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

            if (useMainStore().order.damage.isRepair === undefined) return windshieldOptions;

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

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

                if (
                    useMainStore().order.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 (
                useMainStore().order.damage.glassToReplace?.some((glass) => {
                    return glass.glassLocation === damageLocationsSelected.DRIVER;
                })
            ) {
                doorSides.push(damageLocationsSelected.DRIVERSIDE);
            }

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

            return doorSides;
        },

        getDriverSideReplaceOptionsFromStore() {
            var driverSideReplaceOptions = [];

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

            return driverSideReplaceOptions;
        },

        getPassengerSideReplaceOptionsFromStore() {
            var passengerSideReplaceOptions = [];

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

            return passengerSideReplaceOptions;
        },

        getRearReplaceOptionsFromStore() {
            var rearReplaceOptions = useMainStore().order.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
            );

            return this.navigateForward();
        },

        navigateForward() {
            // If vin already exists, navigate directly to vin-lookup
            if (useMainStore().order.vehicle.vin) {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_WITH_VIN,
                    this.$route
                );
            } else {
                this.$router.navigate(
                    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];
        }
    },

    components: {
        siteHeader,
        siteFooter,
        vehicleBanner,
        siteSubHeader,
        sideDoorOptions,
        damageLocationQuestion,
        windshieldOptions,
        replaceOptionsQuestion,
        Form,
        alert,
    },
};
</script>
