<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition">
            <div class="justify-content-center">
                <siteHeader
                    ref="siteHeader"
                    cmsWidgetName="SiteHeaderWidget" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="policy-endorsements-container iss-heritage-content-container-width">
                    <siteSubHeader
                        ref="siteSubHeader"
                        cmsWidgetName="SiteSubHeaderWidget"
                        class="site-sub-header-container" />
                    <buttonQuestion
                        v-if="educatorEndorsement"
                        ref="schoolPropertyQuestion"
                        v-model="schoolPropertyAnswer"
                        class="radioQuestion windshield-chip-count-question mb-4"
                        cmsWidgetName="SchoolPropertyQuestion"
                        :questionText="schoolPropertyQuestionText"
                        :answers="schoolPropertyAnswersFromCms"
                        groupName="schoolProperty"
                        buttonID="schoolPropertyQuestion"
                        buttonTypeString="listButtonHorizontal"
                        isRequired
                        :validationRules="rules.selectionRequired">
                    </buttonQuestion>
                    <buttonQuestion
                        v-if="parkingGuardEndorsement"
                        ref="parkingLotQuestion"
                        v-model="parkingLotAnswer"
                        class="radioQuestion windshield-chip-count-question"
                        cmsWidgetName="ParkingLotQuestion"
                        :questionText="parkingLotQuestionText"
                        :answers="parkingLotAnswersFromCms"
                        groupName="parkingLot"
                        buttonID="parkingLotQuestion"
                        buttonTypeString="listButtonHorizontal"
                        isRequired
                        :validationRules="rules.selectionRequired">
                    </buttonQuestion>
                    <siteFooter
                        ref="siteFooter"
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardActionDisabled="!meta.valid"
                        @forwardClicked="forwardButtonAction"
                        @backClicked="navigateBack" />
                </div>
            </div>
        </div>
    </Form>
</template>
<script>
// Components
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import buttonQuestion from '@/digital-components/button-question/button-question.vue';

// Supporting files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';
import { Form } from 'vee-validate';
import BaseFormMixin from '@/mixins/base-form-mixin.js';
import globalRules from '@/constants/global-rules.js';
import endorsementOptions from '@/constants/endorsement-options.js';

import { useMainStore } from '@/store';

export default {
    name: 'policy-endorsements',
    components: {
        siteHeader,
        siteSubHeader,
        siteFooter,
        buttonQuestion,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form
    },
    mixins: [BaseFormMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);
        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: 'cmsContent',
                promise: cmsContentPromise
            }
        ];
        // use resultMap to populate layout content.
        const resultMap = await settleAllPromises(promiseResultMap);
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    emits: ['update:modelValue'],
    setup() {
        const mainStore = useMainStore();

        return { mainStore };
    },
    data() {
        return {
            questionAnswersArray: [],
            schoolPropertyAnswer: '',
            parkingLotAnswer: '',
            hasValidCarId:
                this.mainStore.vehicle.carId
                && this.mainStore.vehicle.carId !== '0',
            rules: {
                selectionRequired: globalRules.OPTION_REQUIRED
            }
        };
    },
    computed: {
        schoolPropertyQuestionText() {
            return this.getCmsContent('SchoolPropertyQuestion', 'QuestionText');
        },
        schoolPropertyAnswersFromCms() {
            return this.getCmsContent('SchoolPropertyQuestion', 'Answers');
        },
        parkingLotQuestionText() {
            return this.getCmsContent('ParkingLotQuestion', 'QuestionText');
        },
        parkingLotAnswersFromCms() {
            return this.getCmsContent('ParkingLotQuestion', 'Answers');
        },
        educatorEndorsement() {
            return (
                useMainStore().order.policy.endorsements?.includes(endorsementOptions.EDUCATOR) ?? false
            );
        },
        parkingGuardEndorsement() {
            return (
                useMainStore().order.policy.endorsements?.includes(endorsementOptions.PARKING_GUARD) ?? false
            );
        }
    },
    methods: {
        async forwardButtonAction() {
            // TO DO: remove hard coding and update data format once service returns endorsement questions
            if (this.educatorEndorsement) {
                this.questionAnswersArray.push({
                    questionNum: 1,
                    endorsementName: endorsementOptions.EDUCATOR,
                    questionText: this.schoolPropertyQuestionText,
                    selectedAnswer: this.schoolPropertyAnswer
                });
            }
            if (this.parkingGuardEndorsement) {
                this.questionAnswersArray.push({
                    questionNum: 2,
                    endorsementName: endorsementOptions.PARKING_GUARD,
                    questionText: this.parkingLotQuestionText,
                    selectedAnswer: this.parkingLotAnswer
                });
            }

            // save answers to store as order.policy.endorsementQuestionAnswers
            useMainStore().saveEndorsementQuestionAnswers(this.questionAnswersArray);

            return this.navigateForward();
        },
        navigateForward() {
            if (!this.hasValidCarId) {
                this.$router.navigate(
                    this.navigationScenarios
                        .CLICKED_FORWARD_WITH_CAR_ID_NOT_FOUND,
                    this.$route
                );
            } else {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD,
                    this.$route
                );
            }
        }
    }
};
</script>

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

:deep(.subheader-primary) {
    line-height: 1.5rem;

    h5 {
        line-height: 1.5rem;
        span {
            font-size: 1rem;
            font-weight: 500;
            line-height: 1.5rem;
        }
    }
}

:deep(.subheader-secondary) {
    line-height: 1.5rem;
    margin-top: 0.625rem;
    p {
        font-size: 1rem;
        font-weight: 400;
        line-height: 1.5rem;
    }
}

:deep(.subheader-secondary.justify-content-center) {
    p {
        text-align: left;
    }
    justify-content: left !important;
    padding-left: 0;
    padding-right: 0;
}

</style>
