<template>
	<Form
		@submit="onSubmit"
		@invalid-submit="onInvalidSubmit"
		ref="theForm"
		v-slot="{ meta }"
		autocomplete="off" >
		<div class="container-fluid shadow rounded-3 p-2 position-relative make-tall px-5">
			<funnelHeader cmsWidgetName="FunnelHeaderWidget" ref="funnelHeader" />
			<vehicleBanner ref="vehicleBanner" :displayGenericVehicleImage=false />
			<funnelSubHeader cmsWidgetName="FunnelSubHeaderWidget" ref="funnelSubHeader" />		
			<customerQuestions ref="customerQuestions" v-model="customerQuestions" />
			<alert ref="alertVinNotFound" v-show="displayVinNotFoundAlert"
				class="my-3"
				cmsWidgetName="AlertVinNotFoundWidget"
				alertClass="alert-danger"
				v-bind:isDismissible="false"
			/>
			<alert ref="alertMatchedDifferentVehicle" v-show="displayMatchedDifferentVehicleAlert"
				class="my-3"
				:manualHeadline="AlertMatchedDifferentVehicleHeader"
				:manualCopy="AlertMatchedDifferentVehicleBody"
				alertClass="alert-warning"
				v-bind:isDismissible="false"
			/>			
			<alert ref="alertNonServiceableZip" v-show="displayNonServiceableZipAlert"
				class="my-3"
				alertClass="alert-danger"
				:manualHeadline="AlertNonServiceableZipHeader"
				:manualCopy="AlertNonServiceableZipBody"
				v-bind:isDismissible="false"
			/>			
			<alert ref="alertVinLookupsByHomeAddressNotAllowed" v-show="displayVinLookupByHomeAddressNotAllowedAlert"
				class="my-3"
				cmsWidgetName="AlertVinLookupsByHomeAddressNotAllowedWidget"
				alertClass="alert-danger"
				v-bind:isDismissible="false"
			/>
			<transition name="fade" mode="out-in">
				<div class="service-zip-field" v-if="showServiceZipField" aria-live="polite">
					<div class="row my-4">
						<div class="col">
							<textboxQuestion cmsWidgetName="ServiceZipQuestionWidget" v-model="serviceZip" ref="serviceZip" inputId="7add1b26df344f2caf1678de5797803f" aria-haspopup="" mask="#####" disableAutoFill validationRules="service-zip-required|service-zip-format" />
						</div>
					</div>
				</div>
			</transition>								
			<funnel-footer
				cmsWidgetName="FunnelFooterWidget"
				ref="funnelFooter"
				:isDisabled="!meta.valid"
				@ForwardClicked="forwardButtonAction"
				:isForwardActionDisabled="!meta.valid"
			/>
			
		</div>
	</Form>
</template>

<script>

// Components
import funnelHeader from "@/common-components/funnel-header/funnel-header";
import funnelFooter from "@/common-components/funnel-footer/funnel-footer";
import vehicleBanner from "@/common-components/vehicle-banner/vehicle-banner";
import funnelSubHeader from "@/common-components/funnel-sub-header/funnel-sub-header";
import customerQuestions from "@/layouts/address-lookup/customer-questions/customer-questions";
import alert from "@/ux-components/alert/alert";
import textboxQuestion from "@/common-components/textbox-question/textbox-question";

import { Form } from "vee-validate";
import { defineRule } from "vee-validate";
import { required } from "@/helpers/validation-rules";
import { regex } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";

// Supporting files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import store from "@/store";
import { storeActions } from "@/constants/store-actions";
import { storeMutations } from "@/constants/store-mutations";
import baseMixin from "@/mixins/base-mixin";
import { navigateToHeritageFunnel } from "@/helpers/heritage-integration/navigation-helper";
import { getDamageString, isGlassAvailableForCarId } from "@/helpers/damage-helper";

defineRule("service-zip-required", required(errorMessages.SERVICE_ZIP_REQUIRED));
defineRule("service-zip-format", regex(/(^\d{5}$)|(^\d{5}-\d{4}$)/, errorMessages.SERVICE_ZIP_FORMAT));

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

		// 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: {
				addressQuestions: {
					streetAddress: this.getRegistrationAddressFromStore(),
					city: this.getRegistrationCityFromStore(),
					state: this.getRegistrationStateFromStore(),
					zip: this.getRegistrationZipFromStore(),
				},
				firstName: this.getRegistrationFirstNameFromStore(),
				lastName: this.getRegistrationLastNameFromStore(),
				emailAddress: this.getEmailFromStore(),
			}, 
			serviceZip: this.getServiceZipFromStore(),
			displayNonServiceableZipAlert: false,
			displayVinNotFoundAlert: false,
			displayMatchedDifferentVehicleAlert: false,
			displayVinLookupByHomeAddressNotAllowedAlert: false,
			previousCarIdFound: "", 
			customAlertData: {}, 
		}
	},
	methods: {
		arePagePrerequisitesValid() {
			return store.getters.vehicle.carId !== null;
		},
		resetDependentState() {
			store.commit(storeMutations.UPDATE_REGISTRATION_LICENSE_PLATE, null);
			store.dispatch(storeActions.RESET_PARTS_STATE_AND_DEPENDENCIES);
		},
		backButtonAction() {
			// route to move backwards
			this.$router.navigate(
				this.navigationScenarios.CLICKED_BACK,
				this.$route
			);
		},
		getRegistrationAddressFromStore() {
			return store.getters.vehicle.registration.address;
		},
		getRegistrationCityFromStore() {
			return store.getters.vehicle.registration.city;
		},
		getRegistrationStateFromStore() {
			return store.getters.vehicle.registration.state;
		},
		getRegistrationZipFromStore() {
			return store.getters.vehicle.registration.zipCode;
		},
		getRegistrationFirstNameFromStore() {
			return store.getters.vehicle.registration.firstName;
		},
		getRegistrationLastNameFromStore() {
			return store.getters.vehicle.registration.lastName;
		},						
		getEmailFromStore() {
			return store.getters.order.customer.emailAddress;
		},
		getServiceZipFromStore() {
			return store.getters.order.serviceLocation.zip;
		},
		async forwardButtonAction() {
			this.resetWarningsAndErrors();

			// Lookup VIN(s) with the provided address
			const vinLookup = await this.lookupVin(
				this.customerQuestions.lastName, 
				this.customerQuestions.addressQuestions.streetAddress, 
				this.customerQuestions.addressQuestions.zip, 
				this.customerQuestions.addressQuestions.state
			);

			if (!vinLookup.data.isStatePermissible) {				
				// State Restrictions forbid lookup by address
				this.displayVinLookupByHomeAddressNotAllowedAlert = true;
				this.$refs.funnelFooter.removeLoader();
				return;
			}
			
			// Validate if the original or service zip provided is serviceable
			const zipValidation = this.serviceZip ? await this.validateZip(this.serviceZip) : await this.validateZip(this.customerQuestions.addressQuestions.zip);
			if (!zipValidation.data.isServiceable) {
				this.displayNonServiceableZipAlert = true;
				this.showServiceZipField = true;
				this.$refs.funnelFooter.removeLoader();
			} 

			const carEntered = store.getters.vehicle;
			const carsFound = vinLookup.data.vinVehicles;			
			if (carsFound.length == 0) {
				// No VINs found					
				this.displayVinNotFoundAlert = true;
				this.$refs.funnelFooter.removeLoader();
				return;				
			} else if (carsFound.length == 1) {			
				var carFound = carsFound[0].vehicle;

				if (carEntered.carId == carFound.carId || carFound.carId == this.previousCarIdFound) {
					// update data
					this.updateVehicleInfo(carFound.vin, carFound);
					this.updateCustomerInfo();

					// navigate forward
					this.navigateForward(carEntered, carsFound);					
				} else {
					// Display Alert
					this.customAlertData.vehicleInfo = carFound;
					this.displayMatchedDifferentVehicleAlert = true;

					// Update button "Continue with..."
					this.$refs.funnelFooter.updateButtonText(`Continue with ${carFound.year} ${carFound.make} ${carFound.model}`);				
					this.$refs.funnelFooter.removeLoader();
				} 

				this.previousCarIdFound = carFound.carId;

			} else if (vinLookup.data.vinVehicles.length > 1) {
				this.updateCustomerInfo();

				// navigate forward
				this.navigateForward(carEntered, carsFound);				
			}


		},
		resetWarningsAndErrors() {
			this.displayVinNotFoundAlert = false;
			this.displayNonServiceableZipAlert = false;	
			this.displayMatchedDifferentVehicleAlert = false;
			this.displayVinLookupByHomeAddressNotAllowedAlert = false;
		},
		async navigateForward(carEntered, carsFound) {
			if (carsFound.length == 1) {
				// get the damage options for the car that was found
				const carFound = carsFound[0].vehicle;
				const glassOptions = await baseMixin.methods.dispatchNonBlockingStoreAction(
					storeActions.GET_DAMAGE_OPTIONS,
					{ carId: carFound.carId }
				);

				// if the car entered is the same as the car found OR the glass options for the found car match the users damage selections
				if (carEntered.carId == carFound.carId || isGlassAvailableForCarId(carFound.carId)) {
					navigateAfterSaveToHeritageFunnel(this.$route);
				} else {
					// if not then navigate to the "vehicle-damage" page
					this.$router.navigateAfterSave(this.navigationScenarios.CLICKED_FORWARD, this.$route, {}, { displayVehicleChangeAlert: true }, {});					
				}
			} else if (carsFound.length > 1) {
				// if multiple cars were found 
				if (carsFound.find(car => car.carId === carEntered.carId)) {
					// and one of them matches the car id entered
					navigateAfterSaveToHeritageFunnel(this.$route);
				} else {
					// and there is no match, navigate to "address-vehicle" page
					this.$router.navigateAfterSave(this.navigationScenarios.CONTINUING_WITH_MULTIPLE_VEHICLES, this.$route, {}, {}, carsFound);
				}
			} 

		},
		validateZip(zip) {
			return baseMixin.methods.dispatchNonBlockingStoreAction(
				storeActions.VALIDATE_ZIP, 
				{ zip });
		},
		lookupVin(lastName, streetAddress, zip, state) {
			return baseMixin.methods.dispatchNonBlockingStoreAction(
				storeActions.LOOKUP_VIN_BY_ADDRESS,
				{ 
					licenseLastName: lastName, 
					licenseStreetAddress: streetAddress, 
					licenseZip: zip, 
					licenseState: state 
				}, false
			);
		},
		updateVehicleInfo(vin, vehicleInfo) {
			store.commit(storeMutations.UPDATE_VEHICLE_VIN, vin);
			store.commit(storeMutations.UPDATE_YEAR, vehicleInfo.year);
			store.commit(storeMutations.UPDATE_MAKE, vehicleInfo.make);
			store.commit(storeMutations.UPDATE_MODEL, vehicleInfo.model);
			store.commit(storeMutations.UPDATE_STYLE, vehicleInfo.style);
			store.commit(storeMutations.UPDATE_CAR_ID, vehicleInfo.carId);
			store.commit(storeMutations.UPDATE_VEHICLE_CATEGORY, vehicleInfo.category);
			store.commit(storeMutations.UPDATE_VEHICLE_IMAGE_URL, vehicleInfo.imageUrl);
			store.commit(storeMutations.UPDATE_VEHICLE_IMAGE_VIF_NUMBER, vehicleInfo.imageVifNumber);
			store.commit(storeMutations.UPDATE_VEHICLE_IMAGE_COLOR, vehicleInfo.imageColor);
		},		
		updateCustomerInfo() {
			store.commit(storeMutations.UPDATE_REGISTRATION_ADDRESS, this.customerQuestions.addressQuestions.streetAddress);
			store.commit(storeMutations.UPDATE_REGISTRATION_CITY, this.customerQuestions.addressQuestions.city);
			store.commit(storeMutations.UPDATE_REGISTRATION_STATE, this.customerQuestions.addressQuestions.state);
			store.commit(storeMutations.UPDATE_REGISTRATION_ZIP_CODE, this.customerQuestions.addressQuestions.zipCode);
			store.commit(storeMutations.UPDATE_REGISTRATION_FIRST_NAME, this.customerQuestions.firstName);
			store.commit(storeMutations.UPDATE_REGISTRATION_LAST_NAME, this.customerQuestions.lastName);
			store.commit(storeMutations.UPDATE_SERVICE_LOCATION_ZIP, this.serviceZip);			
			store.commit(storeMutations.UPDATE_CUSTOMER_EMAIL_ADDRESS, this.customerQuestions.email);
		},
		
	},
	computed: {
		AlertNonServiceableZipHeader(){
			let zip = this.serviceZip ? this.serviceZip : this.customerQuestions.addressQuestions.zip;
			let text = this.getCmsContent("AlertNonServiceableZipWidget", "HeadlineText").replaceAll("{custom:serviceZip}", zip);
			return text;
		},
		AlertNonServiceableZipBody(){
			return this.getCmsContent("AlertNonServiceableZipWidget", "BodyText");
		},		
		AlertMatchedDifferentVehicleHeader(){
			let text = this.getCmsContent("AlertMatchedDifferentVehicleWidget", "HeadlineText").replaceAll("{custom:glassText}", getDamageString());
			return text;
		},
		AlertMatchedDifferentVehicleBody(){
			let content = this.getCmsContent("AlertMatchedDifferentVehicleWidget", "BodyText");
			content = content.replaceAll("{custom:glassText}", getDamageString());
			let vinYmmFound = `${this.customAlertData?.vehicleInfo?.year} ${this.customAlertData?.vehicleInfo?.make} ${this.customAlertData?.vehicleInfo?.model}`;
			let vinYmmExpected = `${store.getters.vehicle.year} ${store.getters.vehicle.make} ${store.getters.vehicle.model}`;   

			content = content.replaceAll("{custom:vinYmmFound}", vinYmmFound); 
			content = content.replaceAll("{custom:vinYmmExpected}", vinYmmExpected); 			

			return content;
		},		
	},
	watch: {
		customerQuestions: {		
			handler(newValue) {
				// if they modify one of the lookup fields (address, city, state, zip, or lastName), then modify the button text back to “Get my personalized quote”
				this.$refs.funnelFooter.updateButtonText(this.getCmsContent("FunnelFooterWidget", "ForwardButtonText"));
				this.showServiceZipField = false;
				this.resetWarningsAndErrors();
			},
			deep: true
		},
		serviceZip: {
			handler(newValue) {
				// if they modify the service zip, then hide the error message”
				this.displayNonServiceableZipAlert = false;
			},
		}

	},
	components: {
		funnelHeader,
		funnelFooter,
		vehicleBanner,
		funnelSubHeader,
		customerQuestions,
		textboxQuestion,
		alert,
		Form
	},
};
</script>
