<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"
              :showWindshieldDamageTypeQuestion="values.DamageLocationQuestion && values.DamageLocationQuestion.toString().includes('-Windshield')"
              :suppressError="errors.windshieldDamageTypeQuestion && errors.windshieldDamageTypeQuestion.startsWith('checkForRepairAndReplace')"
            />
            <alert
              class="my-3"
              v-if="errors.windshieldDamageTypeQuestion && errors.windshieldDamageTypeQuestion.startsWith('checkForRepairAndReplace')"
              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."
              :isDismissible="false"
            />
            <replaceOptionsQuestion
              ref="driverSideOptions"
              isAvailable
              v-model="driverSideOptionsData"
              groupName="DriverSideReplaceOptionsQuestion"
            />
            <funnel-footer
              ref="funnelFooter"
              :isDisabled="!meta.valid"
            />

            <!-- 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 windshieldOptions from "@/layouts/vehicle-damage/windshield-options/windshield-options";
import alert from "@/ux-components/alert/alert";

import { Form } from 'vee-validate';


// 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";


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.driverSideOptions.initializeComponent(
        resultMap.cmsContent.DriverSideReplaceOptionsQuestion, resultMap.damageOptions.driverSideOptions.availableReplacementOptions
      );
      vm.$refs.damageLocation.initializeComponent(
        resultMap.cmsContent.DamageLocationQuestion, resultMap.damageOptions
      );
      vm.$refs.funnelFooter.initializeComponent(
        resultMap.cmsContent.FunnelFooterWidget
      );
    });
  },
  data(){
    return {
      selectedDamageLocations: [],
      driverSideOptionsData: [],
    }
  },
  components: {
    Form,
    funnelHeader,
    vehicleBanner,
    funnelSubHeader,
    damageLocationQuestion,
    replaceOptionsQuestion,
    funnelFooter,
    windshieldOptions,
    alert,
  },
  methods: {
    arePagePrerequisitesValid() {
      return store.getters.vehicle.carId !== null;
    },
    resetDependentState() {
      // Invokes
      store.dispatch(storeActions.RESET_PARTS_AND_DEPS);
    },
    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();
      }
    },
  },
};
</script>
