<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="page-container-grouped-styles">
            <div class="fade-on-route-transition position-relative">
                <siteHeader cmsWidgetName="SiteHeaderWidget" />
                <div class="main-content-container">
                    <div class="text-center text-color--black pt-5 pb-5 fs-5">
                        <img :src="orderConfirmationImage" />
                        <span
                            class="ms-2"
                            v-html="orderConfirmationHeaderText"></span>
                    </div>
                    <div class="appointment-details">
                        <div>
                            <vehicleBanner
                                cmsWidgetName="VehicleBannerWidget"
                                :displayGenericVehicleImage="false">
                            </vehicleBanner>
                        </div>
                        <div class="appointment-date-time text-center">
                            <p>{{ appointmentDateFormatted }}</p>
                            <p>{{ appointmentTimeFormatted }}</p>
                        </div>
                        <addToCalendar
                            mobileWidgetName="AddToCalendar_Mobile"
                            inShopWidgetName="AddToCalendar_InShop"
                            dropOffWidgetName="AddToCalendar_DropOff"
                            overnightDropOffWidgetName="AddToCalendar_OvernightDropOff"
                            allDayDropOffWidgetName="AddToCalendar_AllDayDropOff"
                            sameDayDropOffWidgetName="AddToCalendar_SameDayDropOff"
                            :serviceLocationFullAddress="serviceLocationFullAddress"
                            :providerFullAddress="providerFullAddress"
                            :appointmentType="appointmentType"
                            :scheduleDate="appointmentDate"
                            :scheduleStartTime="appointmentStartTime"
                            :scheduleEndTime="appointmentEndTime" />
                        <div
                            class="appointment-text text-center lh-base"
                            v-html="appointmentWordingText">
                        </div>
                        <div
                            class="appointment-text text-center lh-base mt-2"
                            v-html="appointmentWordingText2">
                        </div>
                    </div>
                    <hr class="mb-0" />
                    <div>
                        <cartDropdown
                            :showAsPaid="isPayInAdvance"
                            :readOnly="true"
                            :isInitiallyExpanded="false"
                            :showDropdownHeader="true"
                            recyclingModalCmsWidgetName="RecycleModal"
                            servicePackageTitleWidgetName="ServicePackageTitle"
                            :submittedOrder="submittedOrder" />
                    </div>
                    <hr class="mt-0 mb-5" />
                    <div
                        class="email-confirmation-text"
                        v-html="confirmationEmailText" />
                    <siteFooter
                        v-if="carrierUrl"
                        ref="siteFooter"
                        cmsWidgetName="SiteFooterWidget"
                        :isStackedVertically="true"
                        :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 vehicleBanner from '@/iss-components/vehicle-banner/vehicle-banner.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import addToCalendar from '@/layouts/order-confirmation/add-to-calendar/add-to-calendar.vue';
import cartDropdown from '@/iss-components/cart-dropdown/cart-dropdown.vue';

// Supporting files
import { fetchCmsContentForPage, processIfStatements } 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 { useMainStore } from '@/store';
import { get12HourTimeFormat,
    get12HourTimeMobileFormat,
    convertDateStringToDate,
    getDisplayTextForDurationLength } from '@/helpers/date-helper.js';
import { toTitleCase } from '@/helpers/text-helper.js';
import { AppointmentTypeStrings } from '@/constants/schedule-constants';
import applicationConfig from '@/constants/application-config';

export default {
    name: 'order-confirmation',
    components: {
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        siteHeader,
        vehicleBanner,
        siteFooter,
        addToCalendar,
        cartDropdown
    },
    mixins: [BaseFormMixin],
    async beforeRouteEnter(to, from, next) {
        useMainStore().createSubmittedOrder();
        // 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);
        });
    },
    setup() {
        const mainStore = useMainStore();
        const { submittedOrder } = mainStore;
        return { mainStore, submittedOrder };
    },
    computed: {
        carrierName() {
            return this.mainStore.issConfig.clientName;
        },
        carrierUrl() {
            return this.mainStore.issConfig.successReturnURL;
        },
        confirmationEmailText() {
            return this.getCmsContent('EmailConfirmationWordingWidget', 'BodyText')
                ?.replaceAll('{custom:CUSTOMER_PORTAL_URL}', applicationConfig.CUSTOMER_PORTAL_URL)
                ?.replaceAll('{custom:CUSTOMER_PORTAL_LOGIN_TOKEN}', this.submittedOrder.customerPortalLoginToken)
                ?.replaceAll('&lt;', '<')
                ?.replaceAll('&gt;', '>');
        },
        orderConfirmationHeaderText() {
            return this.getCmsContent('OrderConfirmationContent', 'HeaderText');
        },
        orderConfirmationImage() {
            return this.getCmsContent('OrderConfirmationContent', 'Image');
        },
        appointmentType() {
            return this.submittedOrder.serviceLocation.appointmentType;
        },
        appointmentDate() {
            return this.submittedOrder.schedule.date;
        },
        appointmentStartTime() {
            return this.submittedOrder.schedule.startTime;
        },
        appointmentEndTime() {
            return this.submittedOrder.schedule.endTime;
        },
        appointmentDateFormatted() {
            // This conversion ensures we don't get get GMT induced date changes
            const dateObject = convertDateStringToDate(this.appointmentDate);
            // Ex: Tuesday, April 22
            return dateObject.toLocaleDateString('en-us', {
                weekday: 'long',
                month: 'long',
                day: 'numeric'
            });
        },
        appointmentTimeFormatted() {
            const formattedTime = this.formatAppointmentTime(this.appointmentType);
            return formattedTime;
        },
        mobileWordingText() {
            return this.getCmsContent('MobileWordingWidget', 'BodyText');
        },
        mobileWordingText2() {
            return this.getCmsContent('MobileWordingWidget', 'BodyText2');
        },
        dropOffAndInShopWordingText() {
            return this.getCmsContent('DropOffAndInShopWordingWidget', 'BodyText');
        },
        dropOffAndInShopWordingText2() {
            return this.getBodyText2FromCms('DropOffAndInShopWordingWidget');
        },
        serviceLocationAddress() {
            return this.submittedOrder.serviceLocation.address;
        },
        serviceLocationAddress2() {
            return this.submittedOrder.serviceLocation.address2;
        },
        serviceLocationCity() {
            return this.submittedOrder.serviceLocation.city;
        },
        serviceLocationState() {
            return this.submittedOrder.serviceLocation.state;
        },
        serviceLocationZipCode() {
            return this.submittedOrder.serviceLocation.zipCode;
        },
        serviceLocationFullAddress() {
            // eslint-disable-next-line max-len
            return `${this.serviceLocationAddress}, ${this.serviceLocationAddress2 ? `${this.serviceLocationAddress2},` : ''}<br/> ${this.serviceLocationCity}, ${this.serviceLocationState} ${this.serviceLocationZipCode}`;
        },
        providerAddress() {
            return toTitleCase(this.submittedOrder.serviceLocation.provider.address.streetAddress);
        },
        providerCity() {
            return toTitleCase(this.submittedOrder.serviceLocation.provider.address.city);
        },
        providerState() {
            return this.submittedOrder.serviceLocation.provider.address.state;
        },
        providerZipCode() {
            return this.submittedOrder.serviceLocation.provider.address.zipCode;
        },
        providerFullAddress() {
            // eslint-disable-next-line max-len
            return this.submittedOrder.serviceLocation?.provider?.address ? `${this.providerAddress},<br/> ${this.providerCity}, ${this.providerState} ${this.providerZipCode}` : '';
        },
        appointmentWordingText() {
            switch (this.appointmentType) {
                case AppointmentTypeStrings.MOBILE:
                case AppointmentTypeStrings.MOBILE_NOT_ITAC_AND_NOT_NOCOMP:
                    return this.mobileWordingText?.replaceAll(
                        '{custom:address}',
                        this.serviceLocationFullAddress
                    );
                case AppointmentTypeStrings.DROP_OFF:
                    return this.dropOffAndInShopWordingText?.replaceAll(
                        '{custom:address}',
                        this.providerFullAddress
                    );
                case AppointmentTypeStrings.IN_SHOP:
                    return this.dropOffAndInShopWordingText?.replaceAll(
                        '{custom:address}',
                        this.providerFullAddress
                    );
                default:
                    return null;
            }
        },
        appointmentWordingText2() {
            switch (this.appointmentType) {
                case AppointmentTypeStrings.MOBILE:
                case AppointmentTypeStrings.MOBILE_NOT_ITAC_AND_NOT_NOCOMP:
                    return this.mobileWordingText2;
                case AppointmentTypeStrings.DROP_OFF:
                    return this.dropOffAndInShopWordingText2;
                case AppointmentTypeStrings.IN_SHOP:
                    return this.dropOffAndInShopWordingText2?.replaceAll(
                        '{custom:inShopDuration}',
                        this.inShopAppointmentDuration
                    );
                default:
                    return null;
            }
        },
        mobileAppointment() {
            return this.submittedOrder.serviceLocation.appointmentType === AppointmentTypeStrings.MOBILE
                || this.submittedOrder.serviceLocation.appointmentType === AppointmentTypeStrings.MOBILE_NOT_ITAC_AND_NOT_NOCOMP;
        },
        inShopAppointment() {
            return this.submittedOrder.serviceLocation.appointmentType === AppointmentTypeStrings.IN_SHOP;
        },
        dropOffAppointment() {
            return this.submittedOrder.serviceLocation.appointmentType === AppointmentTypeStrings.DROP_OFF;
        },
        inShopAppointmentDuration() {
            const inshopDurationTime = getDisplayTextForDurationLength(
                this.submittedOrder.schedule.jobMinMinutes,
                this.submittedOrder.schedule.jobMaxMinutes
            );
            return inshopDurationTime;
        },
        isPayInAdvance() {
            return this.submittedOrder.payment.isPayInAdvance;
        },
        selectedVaps() {
            return this.submittedOrder.lineItems.vaps;
        }
    },
    mounted() {
        if (this.carrierUrl) {
            this.$refs.siteFooter.updateButtonText(`Go back to ${this.carrierName}`);
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            const hasSubmittedOrder = useMainStore().hasSubmittedOrder();
            if (hasSubmittedOrder) {
                return true;
            }

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

            // Insurance
            const isInsuranceSet = useMainStore().order.payment.isInsurance !== null;

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

            // Contact Info
            const { contactInfo } = useMainStore().order;
            const contactInfoReqs = !!(
                contactInfo.firstName
                && contactInfo.lastName
                && contactInfo.servicePhone
                && contactInfo.emailAddress
            );

            // Payment
            const paymentMethodReqs = useMainStore().order.payment.isPayInAdvance === false;

            return (
                serviceLocationReqs
                && isInsuranceSet
                && scheduleReqs
                && contactInfoReqs
                && paymentMethodReqs
            );
        },
        forwardButtonAction() {
            this.$router.navigateToExternalUrl(this.carrierUrl);
        },
        formatAppointmentTime(appointmentType) {
            switch (appointmentType) {
                case AppointmentTypeStrings.MOBILE:
                case AppointmentTypeStrings.MOBILE_NOT_ITAC_AND_NOT_NOCOMP:
                    // eslint-disable-next-line max-len
                    return `Between ${get12HourTimeMobileFormat(this.appointmentStartTime)} - ${get12HourTimeMobileFormat(this.appointmentEndTime)}`;
                case AppointmentTypeStrings.DROP_OFF:
                    return 'Drop off before 9:30 AM';
                case AppointmentTypeStrings.IN_SHOP:
                    return `at ${get12HourTimeFormat(this.appointmentStartTime)}`;
                default:
                    return null;
            }
        },
        processIfStatements,
        getBodyText2FromCms(cmsWidgetName) {
            const body2Text = this.getCmsContent(cmsWidgetName, 'BodyText2');
            return this.processIfStatements(body2Text, 'custom', this.getCustomValueFromString);
        },
        getCustomValueFromString(str) {
            switch (str) {
                case 'inShopAppointment':
                    return this.inShopAppointment;
                case 'dropOffAppointment':
                    return this.dropOffAppointment;
                default:
                    return null;
            }
        }
    }
};
</script>
<style lang="scss" scoped>
$page-side-padding: 1.5rem;

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

    .main-content-container {
        padding: 0 1.5rem !important;
    }
}

.text-color--black {
    color: $black;
}

.appointment-details {
    margin-bottom: 1.5rem;
    padding: 1rem 1.5rem 1.5rem;
    box-shadow: 0 0.188rem 0.625rem rgb(0 0 0 / 0.2);
    border-radius: 0.313rem;
}

.appointment-date-time P {
    color: $black;
    font-size: $h5-font-size;
    line-height: map-get($spacers, 6);
    margin-bottom: 0;

    + p {
        font-size: map-get($spacers, 4);
        line-height: 1.625rem;
        font-weight: $font-weight-bold;
    }
}

.appointment-text {
    :deep(p) {
        margin: 0;
    }
    :deep(strong) {
        font-weight: $font-weight-bold;
        color: $black;
    }
}

.email-confirmation-text {
    :deep(a) {
        font-weight: $font-weight-bold;
        text-decoration: underline;
    }
    :deep(strong) {
        font-weight: $font-weight-bold;
        color: $black;
    }
}
</style>
