<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="license-plate-lookup-container iss-heritage-content-container-width">
                    <siteSubHeader
                        cmsWidgetName="SiteSubHeaderWidget"
                        class="mt-4"
                        subHeaderMarginClasses="mt-1" />
                    <alert
                        v-if="displayVinNotFoundAlert"
                        ref="alertVinNotFound"
                        class="mt-5"
                        cmsWidgetName="AlertVinNotFoundWidget"
                        alertClass="alert-danger"
                        :isDismissible="false" />
                    <alert
                        v-if="displayMatchedDifferentVehicleAlert"
                        ref="alertMatchedDifferentVehicle"
                        class="mt-5"
                        cmsWidgetName="AlertMatchedDifferentVehicleWidget"
                        :manualHeadline="AlertMatchedDifferentVehicleHeader"
                        :manualCopy="AlertMatchedDifferentVehicleBody"
                        alertClass="alert-warning"
                        :isDismissible="false" />
                    <alert
                        v-if="displayMatchedTwoIdenticalYMMVehicleAlert"
                        ref="alertMatchedTwoIdenticalYMMVehicle"
                        class="mt-5"
                        cmsWidgetName="AlertMatchedTwoIdenticalYMMVehicleWidget"
                        :manualHeadline="
                            AlertMatchedTwoIdenticalYMMVehicleHeader
                        "
                        :manualCopy="AlertMatchedTwoIdenticalYMMVehicleBody"
                        alertClass="alert-warning"
                        :isDismissible="false" />
                    <alert
                        v-if="displayNoServiceAlert"
                        ref="alertNoService"
                        class="mt-5"
                        cmsWidgetName="AlertNoServiceWidget"
                        alertClass="alert-danger"
                        :isDismissable="false" />
                    <textboxQuestion
                        id="license-plate-question-wrapper"
                        v-model="licensePlate"
                        cmsWidgetName="LicensePlateNumberQuestionWidget"
                        isRequired
                        disableAutoFill
                        inputId="license-plate-question"
                        class="mt-4"
                        validationRules="license-plate-required" />
                    <dropdownQuestion
                        ref="state"
                        v-model="licenseState"
                        cmsWidgetName="StateQuestionWidget"
                        inputId="8fdf9dc2e13e430eb57529499dceb3eb"
                        :options="stateOptions"
                        disableAutoFill
                        validationRules="state-required"
                        class="mt-4" />
                    <siteFooter
                        ref="siteFooter"
                        class="mt-5"
                        :isForwardActionDisabled="!meta.valid"
                        cmsWidgetName="SiteFooterWidget"
                        @backClicked="navigateBack"
                        @forwardClicked="forwardButtonAction" />
                </div>
            </div>
        </div>
    </Form>
</template>
<script>
// Import Supporting Files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';
import { useMainStore } from '@/store';
import errorMessages from '@/constants/error-messages';
import { required } from '@/helpers/validation-rules';
import { defineRule, Form } from 'vee-validate';
import {
    getDamageString,
    isGlassAvailableForCarId
} from '@/helpers/damage-helper.js';
import routerParams from '@/router/router-constants/router-params.js';
import states from '@/constants/states';
import showIssLoadingModal from '@/helpers/loading-modal-helper.js';

// Import Component
import baseFormMixin from '@/mixins/base-form-mixin';
import vinPagesMixin from '@/mixins/vin-pages-mixin';

import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import textboxQuestion from '@/digital-components/textbox-question/textbox-question.vue';
import dropdownQuestion from '@/digital-components/dropdown-question/dropdown-question.vue';
import alert from '@/ux-components/alert/alert.vue';

// Define Validation Rules
defineRule(
    'license-plate-required',
    required(errorMessages.LICENSE_PLATE_REQUIRED)
);
defineRule('state-required', required(errorMessages.STATE_REQUIRED));

export default {
    name: 'license-plate-lookup',
    components: {
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        siteFooter,
        siteHeader,
        siteSubHeader,
        textboxQuestion,
        dropdownQuestion,
        alert
    },
    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 {
            activeVehicleLookupAlertType: null,
            vehicleFromLookup: null,
            licensePlate: null,
            licenseState: useMainStore().order.customer.address.state,
            displayVinNotFoundAlert: false,
            displayMatchedDifferentVehicleAlert: false,
            displayMatchedTwoIdenticalYMMVehicleAlert: false,
            previouslyEnteredCarId: '',
            isCarIdDifferent: false,
            customAlertData: {},
            isSelectedGlassAvailableForVehicle: true,
            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 = `${this.mainStore.order.vehicle.year} ${this.mainStore.order.vehicle.make}
             ${this.mainStore.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
                `${this.mainStore.order.vehicle.year} ${this.mainStore.order.vehicle.make} ${this.mainStore.order.vehicle.model} ${this.mainStore.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 = `${this.mainStore.order.vehicle.year} ${this.mainStore.order.vehicle.make}
             ${this.mainStore.order.vehicle.model}`;
            return vinYmmFound.toLowerCase() === vinYmmExpected.toLowerCase();
        },
        stateOptions: {
            get() {
                return states;
            }
        }
    },
    watch: {
        licensePlate() {
            this.$refs.siteFooter.updateButtonText(this.getCmsContent('SiteFooterWidget', 'ForwardButtonText'));
            this.$refs.siteFooter.enableForwardAction();
        },
        registrationZipCode() {
            this.$refs.siteFooter.updateButtonText(this.getCmsContent('SiteFooterWidget', 'ForwardButtonText'));
        },
        licenseState() {
            this.$refs.siteFooter.updateButtonText(this.getCmsContent('SiteFooterWidget', 'ForwardButtonText'));
            this.$refs.siteFooter.enableForwardAction();
        }
    },
    mounted() {
        this.attachCustomEvents();
        this.loadDefaultsFromStore();
    },
    methods: {
        arePagePrerequisitesValid() {
            return useMainStore().order.vehicle.carId !== null;
        },
        loadDefaultsFromStore() {
            this.customerQuestions =
                this.mainStore.customerData.addressQuestions.state;
        },
        attachCustomEvents() {
            this.prependActionToMethod(this, this.forwardButtonAction, () => {
                this.pushEventToGA(
                    this.$route.query[this.queryStrings.ISS_PAGE],
                    this.GaActions.SUBMITTED,
                    this.GaLabels.LICENSE_PLATE_LOOKUP,
                    true
                );
            });
        },
        // NOTE: If form is not valid, this method is not called when 'Continue' button is clicked
        async forwardButtonAction() {
            this.resetWarningsAndErrors();

            // Lookup VIN
            const vinLookupResponse = await useMainStore().lookupVinByPlate(
                this.licensePlate,
                this.licenseState
            );

            // No VIN found
            if (vinLookupResponse.error) {
                this.displayVinNotFoundAlert = true;
                this.previouslyEnteredCarId = null;
                showIssLoadingModal(false);
                return this.$refs.siteFooter.disableForwardButton();
            }

            // Vehicle found from VIN lookup
            const vehicleFromLookup = vinLookupResponse.data.vehicle;
            if (!vehicleFromLookup.canSafeliteService) {
                this.displayNoServiceAlert = true;
                showIssLoadingModal(false);
                return this.$refs.siteFooter.disableForwardButton();
            }

            // Check if the CarId has changed
            this.isCarIdDifferent = vehicleFromLookup.carId !== useMainStore().order.vehicle.carId;
            // Handle changing car
            if (this.isCarIdDifferent && vehicleFromLookup.carId !== this.previouslyEnteredCarId
            ) {
                // Display Alert
                this.previouslyEnteredCarId = vehicleFromLookup.carId;
                this.customAlertData.vehicleInfo = vehicleFromLookup;

                if (this.isTwoIdenticalYMMVehicleFound) {
                    this.displayMatchedTwoIdenticalYMMVehicleAlert = true;
                    this.forwardButtonCarStyle = vehicleFromLookup.style;
                } else {
                    this.displayMatchedDifferentVehicleAlert = true;
                }

                this.isSelectedGlassAvailableForVehicle = await isGlassAvailableForCarId(vehicleFromLookup.carId);
                showIssLoadingModal(false);

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

            // Save vehicle, license plate, and registration information
            useMainStore().saveRegistrationLicensePlateLookup({
                isSelectedGlassAvailableForVehicle: this.isSelectedGlassAvailableForVehicle,
                vehicleInfo: Object.assign(vinLookupResponse.data.vehicle, {
                    vin: vinLookupResponse.data.vin
                }),
                registrationInfo: {
                    licensePlate: this.licensePlate,
                    state: this.licenseState
                }
            });

            return this.navigateForward();
        },
        async navigateForward() {
            // 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 {
                await this.navigateForwardWithSingleCarMatch();
            }
        },
        resetWarningsAndErrors() {
            this.displayVinNotFoundAlert = false;
            this.displayMatchedDifferentVehicleAlert = false;
            this.displayNoServiceAlert = false;
        }
    }
};
</script>

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

        div.alert {
            margin-bottom: 0;
        }
    }
}

#license-plate-question-wrapper .form-test-error {
    /**
    Override extra margin-bottom in the error message in TextboxQuestion
    */
    margin-bottom: 0 !important;
}
</style>
