<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition">
            <div class="justify-content-center">
                <siteHeader cmsWidgetName="SiteHeaderWidget" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="address-lookup-container iss-heritage-content-container-width">
                    <siteSubHeader
                        ref="siteSubHeader"
                        cmsWidgetName="SiteSubHeaderWidget"
                        class="mt-4" />
                    <alert
                        v-if="displayVinNotFoundAlert"
                        ref="alertVinNotFound"
                        class="mb-4 mt-4"
                        cmsWidgetName="AlertVinNotFoundWidget"
                        alertClass="alert-danger"
                        :isDismissible="false" />
                    <alert
                        v-if="displayMatchedDifferentVehicleAlert"
                        ref="alertMatchedDifferentVehicle"
                        class="mb-4 mt-4"
                        cmsWidgetName="AlertMatchedDifferentVehicleWidget"
                        :manualHeadline="AlertMatchedDifferentVehicleHeader"
                        :manualCopy="AlertMatchedDifferentVehicleBody"
                        alertClass="alert-warning"
                        :isDismissible="false" />
                    <alert
                        v-if="displayMatchedTwoIdenticalYMMVehicleAlert"
                        ref="alertMatchedTwoIdenticalYMMVehicle"
                        class="mb-4 mt-4"
                        cmsWidgetName="AlertMatchedTwoIdenticalYMMVehicleWidget"
                        :manualHeadline="AlertMatchedTwoIdenticalYMMVehicleHeader"
                        :manualCopy="AlertMatchedTwoIdenticalYMMVehicleBody"
                        alertClass="alert-warning"
                        :isDismissible="false" />
                    <alert
                        v-if="displayVinLookupByHomeAddressNotAllowedAlert"
                        ref="alertVinLookupsByHomeAddressNotAllowed"
                        class="mt-4"
                        cmsWidgetName="AlertVinLookupsByHomeAddressNotAllowedWidget"
                        alertClass="alert-danger"
                        :isDismissible="false" />
                    <alert
                        v-if="displayNoServiceAlert"
                        ref="alertNoService"
                        class="mt-5"
                        cmsWidgetName="AlertNoServiceWidget"
                        alertClass="alert-danger"
                        :isDismissable="false" />
                    <customerQuestions
                        ref="customerQuestions"
                        v-model="customerQuestions" />
                    <siteFooter
                        ref="siteFooter"
                        class="mt-5"
                        cmsWidgetName="SiteFooterWidget"
                        :isDisabled="!meta.valid"
                        :isForwardActionDisabled="!meta.valid"
                        @ForwardClicked="forwardButtonAction"
                        @backClicked="navigateBack" />
                </div>
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import baseFormMixin from '@/mixins/base-form-mixin';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import customerQuestions from '@/layouts/address-lookup/customer-questions/customer-questions.vue';
import alert from '@/ux-components/alert/alert.vue';

import { Form } from 'vee-validate';

// Supporting files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';
import routerParams from '@/router/router-constants/router-params';
import {
    getDamageString,
    isGlassAvailableForCarId
} from '@/helpers/damage-helper';

import vinPagesMixin from '@/mixins/vin-pages-mixin';
import { useMainStore } from '@/store/index.js';

export default {
    name: 'address-lookup',
    components: {
        siteHeader,
        siteFooter,
        siteSubHeader,
        customerQuestions,
        alert,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form
    },
    mixins: [baseFormMixin, vinPagesMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);

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

        const resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    data() {
        return {
            customerQuestions: useMainStore().customerData,
            displayVinNotFoundAlert: false,
            displayMatchedDifferentVehicleAlert: false,
            displayVinLookupByHomeAddressNotAllowedAlert: false,
            displayMatchedTwoIdenticalYMMVehicleAlert: false,
            previouslyEnteredCarId: '',
            isCarIdDifferent: false,
            isSelectedGlassAvailableForVehicle: true,
            customAlertData: {},
            forwardButtonCarStyle: '',
            displayNoServiceAlert: false
        };
    },
    computed: {
        AlertMatchedDifferentVehicleHeader() {
            return this.getCmsContent(
                'AlertMatchedDifferentVehicleWidget',
                'HeadlineText'
            ).replaceAll('{custom:damage}', getDamageString());
        },
        AlertMatchedDifferentVehicleBody() {
            const vinYmmFound =
                // eslint-disable-next-line max-len
                `${this.customAlertData?.vehicleInfo?.year} ${this.customAlertData?.vehicleInfo?.make} ${this.customAlertData?.vehicleInfo?.model}`;
            const vinYmmExpected = `${useMainStore().order.vehicle.year} ${
                useMainStore().order.vehicle.make
            } ${useMainStore().order.vehicle.model}`;

            return this.getCmsContent(
                'AlertMatchedDifferentVehicleWidget',
                'BodyText'
            )
                .replaceAll('{custom:damage}', getDamageString())
                .replaceAll('{custom:vinYmmFound}', vinYmmFound)
                .replaceAll('{custom:vinYmmExpected}', vinYmmExpected);
        },
        AlertMatchedTwoIdenticalYMMVehicleHeader() {
            return this.getCmsContent(
                'AlertMatchedTwoIdenticalYMMVehicleWidget',
                'HeadlineText'
            ).replaceAll('{custom:damage}', getDamageString());
        },
        AlertMatchedTwoIdenticalYMMVehicleBody() {
            const vinYmmsFound =
                // eslint-disable-next-line max-len
                `${this.customAlertData?.vehicleInfo?.year} ${this.customAlertData?.vehicleInfo?.make} ${this.customAlertData?.vehicleInfo?.model} ${this.customAlertData?.vehicleInfo?.style}`;
            const vinYmmsExpected =
                // eslint-disable-next-line max-len
                `${useMainStore().order.vehicle.year} ${useMainStore().order.vehicle.make} ${useMainStore().order.vehicle.model} ${useMainStore().order.vehicle.style}`;

            return this.getCmsContent(
                'AlertMatchedTwoIdenticalYMMVehicleWidget',
                'BodyText'
            )
                .replaceAll('{custom:damage}', getDamageString())
                .replaceAll('{custom:vinYmmsFound}', vinYmmsFound)
                .replaceAll('{custom:vinYmmsExpected}', vinYmmsExpected);
        },
        isTwoIdenticalYMMVehicleFound() {
            const vinYmmFound =
                // eslint-disable-next-line max-len
                `${this.customAlertData?.vehicleInfo?.year} ${this.customAlertData?.vehicleInfo?.make} ${this.customAlertData?.vehicleInfo?.model}`;
            const vinYmmExpected = `${useMainStore().order.vehicle.year} ${
                useMainStore().order.vehicle.make
            } ${useMainStore().order.vehicle.model}`;
            return vinYmmFound.toLowerCase() === vinYmmExpected.toLowerCase();
        }
    },
    watch: {
        customerQuestions: {
            handler() {
                // if they modify one of the lookup fields (address, city, state, zipCode, or lastName),
                // then modify the button text back to "Get my personalized quote"
                this.$refs.siteFooter.updateButtonText(this.getCmsContent('siteFooterWidget', 'ForwardButtonText'));
                this.resetWarningsAndErrors();
            },
            deep: true
        }
    },
    mounted() {
        this.attachCustomEvents();
    },
    methods: {
        arePagePrerequisitesValid() {
            return useMainStore().order.vehicle.carId !== null;
        },
        attachCustomEvents() {
            this.prependActionToMethod(this, this.forwardButtonAction, () => {
                this.pushEventToGA(
                    this.$route.query[this.queryStrings.ISS_PAGE],
                    this.GaActions.SUBMITTED,
                    this.GaLabels.ADDRESS_LOOKUP,
                    true
                );
            });
        },

        async forwardButtonAction() {
            this.resetWarningsAndErrors();

            // Vehicle info change in the flow, use a variable to keep track and commit to state at the end.
            let vehicleInfoToCommit = {};

            const vinLookupResponse = useMainStore().lookupVinByAddress({
                licenseLastName: this.customerQuestions.lastName,
                licenseStreetAddress:
                    this.customerQuestions.addressQuestions.streetAddress,
                licenseZip: this.customerQuestions.addressQuestions.zipCode,
                licenseState: this.customerQuestions.addressQuestions.state
            });

            // Settle promises and get results
            const promiseResultMap = [
                {
                    resultKey: 'vinLookupResponse',
                    promise: vinLookupResponse
                }
            ];

            const resultMap = await settleAllPromises(promiseResultMap);
            // If VIN Lookup by address is forbidden by State Restrictions then show an alert
            if (!resultMap.vinLookupResponse.isStatePermissible) {
                // State Restrictions forbid lookup by address
                this.displayVinLookupByHomeAddressNotAllowedAlert = true;
                return this.$refs.siteFooter.disableForwardButton();
            }

            const carsFound = resultMap.vinLookupResponse.vinVehicles;

            // Handle cases for different amounts of VINS found for the address.
            if (carsFound.length === 1) {
                // Single VIN found
                const carFound = carsFound[0].vehicle;

                if (!carFound.canSafeliteService) {
                    this.displayNoServiceAlert = true;
                    return this.$refs.siteFooter.disableForwardButton();
                }

                this.isCarIdDifferent = carFound.carId !== useMainStore().order.vehicle.carId;
                if (this.isCarIdDifferent && carFound.carId !== this.previouslyEnteredCarId) {
                    // Display Alert
                    this.previouslyEnteredCarId = carFound.carId;
                    this.customAlertData.vehicleInfo = carFound;
                    if (this.isTwoIdenticalYMMVehicleFound) {
                        this.displayMatchedTwoIdenticalYMMVehicleAlert = true;
                        this.forwardButtonCarStyle = carFound.style;
                    } else {
                        this.displayMatchedDifferentVehicleAlert = true;
                    }

                    this.isSelectedGlassAvailableForVehicle =
                        await isGlassAvailableForCarId(carFound.carId);

                    // Update button "Continue with..."
                    return this.$refs.siteFooter
                        // eslint-disable-next-line max-len
                        .updateButtonText(`Continue with ${carFound.year} ${carFound.make} ${carFound.model} ${this.forwardButtonCarStyle}`);
                }

                // update data
                vehicleInfoToCommit = Object.assign(carFound, {
                    vin: carsFound[0].vin
                });
            } else if (carsFound.length > 1) {
                // If multiple cars were found and one and only one of them matches the carId entered, save the vehicle info
                const matchingCars = carsFound.filter((vin) =>
                    vin.vehicle.carId === useMainStore().order.vehicle.carId);

                if (matchingCars.length === 1) {
                    vehicleInfoToCommit = Object.assign(
                        matchingCars[0].vehicle,
                        {
                            vin: matchingCars[0].vin
                        }
                    );
                }
            } else {
                // No VINS found.
                this.displayVinNotFoundAlert = true;
                return this.$refs.siteFooter.disableForwardButton();
            }

            // Save vehicle, customer, service and registration information
            await useMainStore().saveRegistrationAddressLookup(
                {
                    isSelectedGlassAvailableForVehicle:
                        this.isSelectedGlassAvailableForVehicle,
                    vehicleInfo:
                        Object.keys(vehicleInfoToCommit).length === 0
                            ? null
                            : vehicleInfoToCommit,
                    registrationInfo: {
                        firstName: this.customerQuestions.firstName,
                        lastName: this.customerQuestions.lastName,
                        address:
                            this.customerQuestions.addressQuestions
                                .streetAddress,
                        city: this.customerQuestions.addressQuestions.city,
                        state: this.customerQuestions.addressQuestions.state,
                        zipCode:
                            this.customerQuestions.addressQuestions.zipCode
                    }
                },
                false
            );

            return this.navigateForward(carsFound);
        },
        async navigateForward(carsFound) {
            // Match vehicles found to vehicles in state.
            const matchingCars = carsFound.filter((car) =>
                car.vehicle.carId === useMainStore().order.vehicle.carId);

            // If a different vehicle is found than the one entered and the selected glass
            // is not available for that vehicle then navigate back to "vehicle-damage"
            // display vehicle changed alert on that page.
            if (
                this.isCarIdDifferent
                && !this.isSelectedGlassAvailableForVehicle
            ) {
                this.$router.navigate(
                    this.navigationScenarios.SELECTED_VIN_WITH_MISMATCHED_GLASS,
                    this.$route,
                    {},
                    { [routerParams.DISPLAY_VEHICLE_CHANGE_ALERT]: true }
                );
            } else if (matchingCars.length === 1) {
                await this.navigateForwardWithSingleCarMatch();
            } else {
                this.$router.navigate(
                    this.navigationScenarios
                        .CLICKED_FORWARD_WITH_MULTIPLE_VEHICLES,
                    this.$route,
                    {},
                    {},
                    carsFound
                );
            }
        },
        resetWarningsAndErrors() {
            this.displayVinNotFoundAlert = false;
            this.displayMatchedDifferentVehicleAlert = false;
            this.displayVinLookupByHomeAddressNotAllowedAlert = false;
            this.displayNoServiceAlert = false;
            this.$refs.siteFooter.enableForwardAction();
        }
    }
};
</script>

<style lang="scss" scoped>
.iss-heritage-container-width {
    .address-lookup-container {
        position: relative;
        min-height: 1px;
        padding-left: .9375rem;
        padding-right: .9375rem;
    }
}
</style>
