<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="page-container-grouped-styles">
            <siteHeader
                ref="siteHeader"
                cmsWidgetName="SiteHeaderWidget" />
            <vehicleBanner
                cmsWidgetName="VehicleBannerWidget"
                :displayGenericVehicleImage="false" />
            <siteSubHeader
                class="mb-5 mt-4 px-3"
                cmsWidgetName="SiteSubHeaderWidget"
                subHeaderClasses="mt-2" />
            <div class="main-content-container">
                <hr class="my-0" />
                <reviewDropdown ref="reviewDropdown" />
                <hr class="my-0" />
                <cartDropdown
                    :showAsPaid="false"
                    :amountDueLabel="amountDueText"
                    :deductibleLabel="deductibleLabel"
                    :basePriceLabel="basePriceLabel"
                    :servicePackageLabel="serviceLabel"
                    :readOnly="false" />
                <hr class="mt-0 mb-5" />
                <div>Pia Alert Placeholder</div>
                <paymentMethodQuestion
                        v-model="paymentMethodInternalModel"
                        cmsWidgetName="PaymentMethodWidget"
                        :validationRules="rules.optionRequired" />
                <div>Pia Disabled Placeholder</div>
                <siteFooter
                    ref="siteFooter"
                    cmsWidgetName="SiteFooterWidget"
                    :isForwardActionDisabled="!meta.valid"
                    :isStackedVertically="true"
                    @backClicked="navigateBack"
                    @ForwardClicked="forwardButtonAction" />
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import baseFormMixin from '@/mixins/base-form-mixin';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import reviewDropdown from '@/layouts/payment-method/review-dropdown/review-dropdown.vue';
import cartDropdown from '@/iss-components/cart-dropdown/cart-dropdown.vue';
import paymentMethodQuestion from '@/layouts/payment-method/payment-method-question/payment-method-question.vue';

// Supporting Items
import settleAllPromises from '@/helpers/layout-helper';
import { useMainStore } from '@/store';
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import { paymentMethods } from '@/constants/payment-method-constants';
import globalRules from '@/constants/global-rules';
import { Form } from 'vee-validate';
import widgetFields from '@/constants/cms-widget-fields.js';

import { AppointmentTypeStrings } from '@/constants/schedule-constants';

export default {
    name: 'payment-method',
    components: {
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        siteHeader,
        siteSubHeader,
        siteFooter,
        reviewDropdown,
        cartDropdown,
        paymentMethodQuestion
    },
    mixins: [baseFormMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);
        const reviewDropdownPromise = reviewDropdown.methods.loadInitialData();

        const promiseResultMap = [
            {
                resultKey: 'cmsContent',
                promise: cmsContentPromise
            },
            {
                resultKey: 'reviewDropdownData',
                promise: reviewDropdownPromise
            }
        ];

        const resultMap = await settleAllPromises(promiseResultMap);

        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);

            vm.updateFooterButtonText(vm.customCallToActionButtonCopy);

            vm.$refs.reviewDropdown.initializeComponent(resultMap.reviewDropdownData);
        });
    },
    data() {
        return {
            paymentMethodInternalModel: this.getPaymentMethodFromStore(),
            rules: {
                optionRequired: globalRules.OPTION_REQUIRED
            },
            widget: {
                amountDue: 'AmountDueTextWidget',
                deductible: 'DeductibleWidget',
                basePrice: 'BasePriceWidget'
            }
        };
    },
    computed: {
        customCallToActionButtonCopy() {
            switch (this.paymentMethod) {
                case paymentMethods.CREDIT_CARD:
                    return 'Continue to checkout';
                case paymentMethods.PAYPAL:
                    return 'Continue to Paypal';
                case paymentMethods.AFTERPAY:
                    return 'Continue to Afterpay';
                default:
                    return null;
            }
        },
        paymentMethod() {
            return this.paymentMethodInternalModel;
        },
        amountDueText() {
            return this.getCmsContent(this.widget.amountDue, widgetFields.TEXT_BLOCK_WIDGET.TEXT);
        },
        deductibleLabel() {
            return this.getCmsContent(this.widget.deductible, widgetFields.TEXT_BLOCK_WIDGET.TEXT);
        },
        basePriceLabel() {
            return this.getCmsContent(this.widget.basePrice, widgetFields.TEXT_BLOCK_WIDGET.TEXT);
        },
        // TODO
        serviceLabel() {
            return 'Standard service';
        }
    },
    watch: {
        customCallToActionButtonCopy(newValue) {
            this.updateFooterButtonText(newValue);
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            // Vehicle
            const { vehicle } = useMainStore().order;
            const vehicleReqs = !!(vehicle.year && vehicle.make && vehicle.model && vehicle.style);

            // Damage
            const { isRepair, numberOfChips, glassToReplace } = useMainStore().order.damage;
            const damageReqs = !!(
                (isRepair && numberOfChips)
                || (!isRepair && glassToReplace?.length)
            );

            // Service Package
            const { lineItems } = useMainStore().order;
            const packageReqs = !!(
                (isRepair || lineItems.glassParts)
                && lineItems.supportingItems
            );

            // Service Location
            const { serviceLocation } = useMainStore().order;
            const mobileReqs = !!(
                serviceLocation.address
                && serviceLocation.city
                && serviceLocation.state
                && serviceLocation.zipCode
            );

            const providerLocation = serviceLocation.provider.address;
            const dropOffInshopReqs = !!(
                providerLocation.streetAddress
                && providerLocation.city
                && providerLocation.state
                && providerLocation.zipCode
            );

            const isMobile = serviceLocation.appointmentType === AppointmentTypeStrings.MOBILE
             || serviceLocation.appointmentType === AppointmentTypeStrings.MOBILE_NOT_ITAC_AND_NOT_NOCOMP;
            const serviceLocationReqs =
                (isMobile && mobileReqs) || (!isMobile && dropOffInshopReqs);

            // Schedule
            const { date, startTime, endTime, jobMaxMinutes, jobMinMinutes } = useMainStore().order.schedule;
            const scheduleReqs = !!(
                date
                && startTime
                && endTime
                && jobMaxMinutes
                && jobMinMinutes
            );

            // Customer
            const { firstName, lastName, phoneNumber, emailAddress } = useMainStore().order.customer;
            const customerReqs = !!(
                firstName
                && lastName
                && phoneNumber
                && emailAddress
            );

            return (
                vehicleReqs
                && damageReqs
                && packageReqs
                && serviceLocationReqs
                && scheduleReqs
                && customerReqs
            );
        },
        getPaymentMethodFromStore() {
            const { payInAdvanceType } = useMainStore().order.payment;
            const isPayInAdvance = useMainStore().order.payment.isPayInAdvance && !!payInAdvanceType;

            return isPayInAdvance ? payInAdvanceType : paymentMethods.PAY_AT_TIME_OF_SERVICE;
        },
        updateFooterButtonText(newValue) {
            this.$refs.siteFooter.updateButtonText(newValue);
        },
        async forwardButtonAction() {
            await useMainStore().savePaymentMethodChoice(this.paymentMethod);

            if (this.paymentMethod === paymentMethods.PAY_AT_TIME_OF_SERVICE) {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD,
                    this.$route
                );
            } else {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_PAY_NOW,
                    this.$route
                );
            }
        }
    }
};
</script>

<style lang="scss" scoped>
$page-side-padding: 1.5rem;

.page-container-grouped-styles {
    overflow: auto;

    .main-content-container {
        padding: 0 1.5rem !important;
    }
}
</style>
