<template>
    <div class="container-fluid shadow rounded-3 p-2 position-relative make-tall">
        <funnelHeader ref="funnelHeader" />
        <vehicleBanner ref="vehicleBanner" :displayGenericVehicleImage=false />
        <funnelSubHeader ref="funnelSubHeader" />
        <Form
          @submit="onSubmit"
          @invalid-submit="onInvalidSubmit"
          ref="theForm"
          v-slot="{ values, meta, errors }"
        >
            <damageLocationQuestion
              ref="damageLocation"
              v-model="selectedDamageLocations"
              groupName="DamageLocationQuestion"
            />
            <windshieldOptions
              ref="windshieldOptions" 
              v-model="selectedWindshieldOptions"
              :hasRepairReplaceConflict="hasRepairReplaceConflict"
              :selectedDamageLocations="selectedDamageLocations"
            />
            <alert
              class="my-3"
              v-show="hasRepairReplaceConflict"
              alertClass="alert-danger"
              alertHeadline="You'll need to schedule separate appointments"
              alertCopy="Vehicle service requiring both glass repair and replacement must be scheduled separately, as they're performed by different technicians. Continue scheduling your first service now, and then come back to schedule the second service."
              :isDismissible="false"
            />
            <sideDoorOptions 
              ref="sideDoorOptions"
              groupName="SideDoorSideQuestion"
              v-model="sideDoorOptionsData"
              v-show="!hasRepairReplaceConflict"
              :selectedDamageLocations="selectedDamageLocations"
            />
            <replaceOptionsQuestion
              ref="backGlassOptions"
              :isAvailable="isRearWindowDamageLocation && !hasRepairReplaceConflict"
              v-model="selectedRearReplaceOptions"
              groupName="BackGlassReplaceOptionsQuestion"
              validationRules="replace-options-required"
            />
            <funnel-footer
              ref="funnelFooter"
              :isForwardActionDisabled="!meta.valid"
              @back-clicked="backButtonAction"
              @ForwardClicked="forwardButtonAction"
            />

            <!-- KEEP TEMPORARILY FOR TROUBLESHOOTING VALIDATION  -->
              <div class="g-2 mt-6 mx-4 w-25 position-fixed fixed-top">
              <p>Current Form, values:</p>
              <pre>{{ values }}</pre>
              <p>Errors:</p>
              <pre>{{ errors }}</pre>
              <p>Is Form Valid? (Meta.valid):</p>
              <pre>{{ meta.valid }}</pre>
            </div>

        </Form>
    </div>
</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 replaceOptionsQuestion from "@/layouts/vehicle-damage/replace-options-question/replace-options-question";
import damageLocationQuestion from "@/layouts/vehicle-damage/damage-location-question/damage-location-question";
import sideDoorOptions from "@/layouts/vehicle-damage/side-door-options/side-door-options";
import windshieldOptions from "@/layouts/vehicle-damage/windshield-options/windshield-options";
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 store from "@/store";
import baseMixin from "@/mixins/base-mixin";
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";

// DEFINE VALIDATION RULES
defineRule("replace-options-required", required(errorMessages.REPLACE_OPTIONS_REQUIRED));

export default {
  name: "form-test",
  async beforeRouteEnter(to, from, next) {
    // Call APIs
    const cmsContentPromise = fetchCmsContentForPage('vehicle-damage');
    const damageOptionsPromise =
      baseMixin.methods.dispatchNonBlockingStoreAction(
        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.$refs.funnelHeader.initializeComponent(
        resultMap.cmsContent.FunnelHeaderWidget
      );
      vm.$refs.vehicleBanner.initializeComponent(
        resultMap.cmsContent.VehicleBannerWidget
      );
      vm.$refs.funnelSubHeader.initializeComponent(
        resultMap.cmsContent.FunnelSubHeaderWidget
      );
      vm.$refs.damageLocation.initializeComponent(
        resultMap.cmsContent.DamageLocationQuestion, resultMap.damageOptions
      );
      vm.$refs.sideDoorOptions.initializeComponent(
        resultMap.cmsContent.SideDoorSideQuestion, resultMap.cmsContent.DriverSideReplaceOptionsQuestion, resultMap.cmsContent.PassengerSideReplaceOptionsQuestion, resultMap.damageOptions.driverSideOptions.availableReplacementOptions, resultMap.damageOptions.passengerSideOptions.availableReplacementOptions
      );
      vm.$refs.windshieldOptions.initializeComponent(
        resultMap.cmsContent.WindshieldDamageTypeQuestion, resultMap.cmsContent.WindshieldChipCountQuestion,
        resultMap.cmsContent.WindshieldReplaceOptionsQuestion, resultMap.damageOptions.windshieldOptions.availableReplacementOptions
      );
      vm.$refs.backGlassOptions.initializeComponent(
        resultMap.cmsContent.RearReplaceOptionsQuestion, resultMap.damageOptions.backGlassOptions.availableReplacementOptions
      );
      vm.$refs.funnelFooter.initializeComponent(
        resultMap.cmsContent.FunnelFooterWidget
      );
    });
  },
  data(){
    return {
      selectedDamageLocations: [],
      sideDoorOptionsData: {
        selectedDoorSides: [],
        selectedDriverSideReplaceOptions: [],
        selectedPassengerSideReplaceOptions: []
      },
      selectedWindshieldOptions: [],
      selectedRearReplaceOptions: [],
    }
  },
  methods: {
    arePagePrerequisitesValid() {
      return store.getters.vehicle.carId !== null;
    },
    resetDependentState() {
      store.dispatch(storeActions.RESET_PARTS_STATE_AND_DEPENDENCIES);
    },
    onSubmit(values) {
      window.alert('Success! Submitted values: ' + JSON.stringify(values, null ,2))
      console.log('submitted: ', JSON.stringify(values, null ,2));
    },
    onInvalidSubmit({ values, errors, results }) {
      // identify the first error field and put focus on it
      console.log("values: ", values);
      console.log("errors: ", errors);
      console.log("results: ", results);
      // get error names array
      const errorNames = errors ? Object.keys(errors) : [];
      const firstErrorEl = errorNames[0];
      if (firstErrorEl) {
        console.log('firstErrorEl: ', firstErrorEl);
        const qsString = "[data-focus-target='" + firstErrorEl + "']";
        document.querySelector(qsString).focus();
      }
    },
  },
  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() {
      if (!this.isWindshieldDamageLocation) return false;
      
      return this.selectedWindshieldOptions.selectedWindshieldDamageType && this.selectedWindshieldOptions.selectedWindshieldDamageType.some(selectedDamageType => 
        {
            return selectedDamageType.toUpperCase() === "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;
    },
  },
  components: {
    funnelHeader,
    funnelFooter,
    vehicleBanner,
    funnelSubHeader,
    sideDoorOptions,
    damageLocationQuestion,
    windshieldOptions,
    replaceOptionsQuestion,
    Form,
    alert,
  },
};
</script>
