<template>
    <transition name="fade" mode="out-in">
        <div class="mobile-location-questions">
            <div class="text-center" :id="componentId">
                <label
                    for="mobileLocationLinkPromptId"
                    :aria-label="mobileLocationLinkPromptText"
                    class="form-label fw-bold w-100 ps-4 pe-4 pt-4 text-black"
                    v-html="mobileLocationLinkPromptText"></label>
                <div class="update-mobile-location-text-link">
                    <textLink
                        ref="mobileLocationLink"
                        id="mobileLocationLinkPromptId"
                        linkType="text"
                        :text="mobileLocationLinkText"
                        href="#!"
                        @click-event="openModal" />
                </div>
                <div v-show="errorMessage" class="row my-1 form-test-error">
                    <span
                        class="d-inline-flex small mt-0 center-error-message"
                        aria-atomic="true"
                        aria-live="polite">
                        {{ errorMessage }}
                    </span>
                </div>
                <textBlock
                    v-if="mobileFeeApplies"
                    :customText="mobileFeeText"
                    cmsWidgetName="MobileFeeDisclaimerWidget"
                    typeStyle="caption" />
            </div>
            <modal
                :ref="modalName"
                :headerText="modalHeaderText"
                :footerButtonText="modalFooterText"
                :onModalOpenedCallback="onModalOpened"
                :onModalClosedCallback="onModalClosed"
                @isModalOpened="setModalStatus"
                @footer-button-event="setMobileLocation">
                <template v-if="isModalOpened">
                    <addressQuestions
                        ref="addressQuestions"
                        v-model="internalModel.addressQuestions"
                        captureApartmentNumberOrBusinessName="true"
                        preserveCityAndStateOnReset="true" />
                    <vehicleProtectedQuestion
                        ref="vehicleProtectedQuestion"
                        v-model="internalModel.isVehicleProtected"
                        cmsWidgetName="VehicleProtectedQuestionWidget" />
                    <textBlock cmsWidgetName="WorkspaceRequirementsWidget" typeStyle="caption" />
                    <alert
                        ref="alertInvalidZip"
                        v-if="displayInvalidZipAlert"
                        class="my-4"
                        cmsWidgetName="AlertInvalidZipWidget"
                        alertClass="alert-danger"
                        v-bind:isDismissible="false" />
                    <alert
                        ref="alertMismatchStateAndZip"
                        v-if="displayMismatchStateAndZipAlert"
                        class="my-4"
                        cmsWidgetName="AlertMismatchStateAndZipWidget"
                        alertClass="alert-danger"
                        v-bind:isDismissible="false" />
                </template>
            </modal>
        </div>
    </transition>
</template>

<script>
// Components
import textLink from "@/ux-components/text-link/text-link";
import textBlock from "@/digital-components/text-block/text-block";
import modal from "@/digital-components/modal/modal";
import alert from "@/ux-components/alert/alert";
import addressQuestions from "@/fmg-components/address-questions/address-questions";
import vehicleProtectedQuestion from "@/layouts/service-location/mobile-location-modal-questions/vehicle-protected-question/vehicle-protected-question";

// Helpers
import { deepClone } from "@/helpers/object-helper";
import {
    getPricedMobileFeePart,
    getPricedRecycleFeePart,
    getServiceabilityDetails,
    getBillToAccountNumber,
} from "@/layouts/service-location/helpers/service-location-helper/service-location-helper";

// Validation
import { useField } from "vee-validate";
import { v4 as uuidv4 } from "uuid";

export default {
    name: "mobile-location-modal-questions",
    emits: [
        "update:modelValue",
        "updated-mobile-fee-part",
        "updated-contains-military-base",
        "updated-bill-to-account-number",
        "setMobileLocationAndProceed",
    ],
    data() {
        return {
            internalModel: deepClone(this.modelValue),
            displayInvalidZipAlert: false,
            isModalOpened: false,
            displayMismatchStateAndZipAlert: false,
        };
    },
    setup(props) {
        const uuid = uuidv4();
        const componentId = !props.customComponentId
            ? `component-${uuid}`
            : props.customComponentId;

        // Integrate this component as a single field with an object for it's value into the page level validation
        const modelValue = deepClone(props).modelValue;
        const initialValue = modelValue;

        const fieldOptions = {
            value: modelValue,
            initialValue: initialValue,
        };

        const { errorMessage, handleChange, meta, validate, errors } = useField(
            componentId,
            props.validationRules,
            fieldOptions
        );

        return {
            componentId,
            errorMessage,
            handleChange,
            validate,
            meta,
            errors,
        };
    },
    props: {
        modelValue: {
            type: Object,
            default: () => ({
                addressQuestions: {
                    streetAddress: "",
                    apartmentNumberOrBusinessName: "",
                    city: "",
                    state: "",
                    zipCode: "",
                },
                isVehicleProtected: null,
            }),
        },
        mobileFeePart: {
            type: Object,
            default: () => ({}),
        },
        linkWidgetName: String,
        modalWidgetName: String,
        alertNonServiceableZipWidgetName: String,
        alertInvalidZipWidgetName: String,
        customComponentId: String,
        validationRules: String,
        mobileFeeApplies: Boolean,
    },
    computed: {
        mobileLocationLinkPromptText() {
            return this.getCmsContent(this.linkWidgetName, "HeaderText");
        },
        mobileLocationLinkText() {
            if (
                this.addressModel.streetAddress &&
                this.addressModel.streetAddress !== "" &&
                this.addressModel.city &&
                this.addressModel.city !== "" &&
                this.addressModel.state &&
                this.addressModel.state !== "" &&
                this.addressModel.zipCode &&
                this.addressModel.zipCode !== "" &&
                this.internalModel.isVehicleProtected !== null
            ) {
                return `${this.addressModel.streetAddress}\n${this.addressModel.city}, ${this.addressModel.state} ${this.addressModel.zipCode}`;
            }
            return this.getCmsContent(this.linkWidgetName, "BodyText");
        },
        mobileFeeText() {
            const cmsContentText = this.getCmsContent("MobileFeeDisclaimerWidget", "Text");
            return cmsContentText.replaceAll("{custom:mobileFee}", this.mobileFee);
        },
        mobileFee() {
            if (!this.mobileFeePart) {
                return 0;
            }

            return (
                this.mobileFeePart.laborAmount +
                this.mobileFeePart.sellingPrice +
                this.mobileFeePart.kitPrice
            );
        },
        modalName() {
            return "MobileLocationModalWidget";
        },
        modalHeaderText() {
            return this.getCmsContent(this.modalWidgetName, "HeaderText");
        },
        modalFooterText() {
            return this.getCmsContent(this.modalWidgetName, "FooterText");
        },
        modal() {
            return this.$refs[this.modalName];
        },
        addressModel: {
            get: function () {
                return this.modelValue.addressQuestions;
            },
        },
    },
    methods: {
        openModal() {
            this.modal.openModal();
        },
        onModalOpened() {
            this.internalModel = deepClone(this.modelValue);
        },
        setModalStatus(isOpened) {
            this.isModalOpened = isOpened;
        },
        closeModal() {
            this.modal.closeModal();
        },
        onModalClosed() {
            this.resetAlerts();
            this.internalModel = deepClone(this.modelValue);
        },
        resetModalButtonStyle() {
            this.modal.resetButtonStyle();
        },
        resetAlerts() {
            this.displayInvalidZipAlert = false;
            this.displayMismatchStateAndZipAlert = false;
        },
        async setMobileLocation() {
            this.resetAlerts();
            // Validate the Zip Code
            const zipCodeData = await this.getZipCodeData(
                this.internalModel.addressQuestions.zipCode,
                "service-location"
            );

            if (!zipCodeData.isValid) {
                this.displayInvalidZipAlert = true;
                this.resetModalButtonStyle();
                return;
            } else if (zipCodeData.state != this.internalModel.addressQuestions.state) {
                this.displayMismatchStateAndZipAlert = true;
                this.resetModalButtonStyle();
                return;
            } else if (
                this.internalModel.addressQuestions.zipCode !==
                this.modelValue.addressQuestions.zipCode
            ) {
                // retrieve mobile fee part
                const serviceZipCode = this.internalModel.addressQuestions.zipCode;
                const mobileFeePart = await getPricedMobileFeePart(
                    serviceZipCode,
                    "service-location"
                );

                // retrieve recycle fee part
                const recycleFeePart = await getPricedRecycleFeePart(
                    serviceZipCode,
                    "service-location"
                );

                // retrieve serviceability details
                const serviceabilityDetails = await getServiceabilityDetails(
                    serviceZipCode,
                    null,
                    "service-location"
                );

                const billToAccountNumber = await getBillToAccountNumber(
                    this.internalModel.zipCodeCtu
                );

                // update content related to service zip code
                this.$emit("updated-mobile-fee-part", mobileFeePart);
                this.$emit("updated-recycle-fee-part", recycleFeePart);
                this.$emit("updated-serviceability", serviceabilityDetails.data);
                this.$emit("updated-contains-military-base", zipCodeData.containsMilitaryBase);
                this.$emit("updated-mobile-ctu", zipCodeData.zipCodeCtu);
                this.$emit("updated-bill-to-account-number", billToAccountNumber);
            }
            // update the page level model
            this.$emit("setMobileLocationAndProceed", this.internalModel);
        },
    },
    watch: {
        modelValue: {
            handler(newValue) {
                this.internalModel = deepClone(newValue);
                this.handleChange(newValue);
            },
            deep: true,
        },
    },
    unmounted() {
        if (this.isModalOpened) this.closeModal();
    },
    components: {
        textLink,
        modal,
        addressQuestions,
        vehicleProtectedQuestion,
        textBlock,
        alert,
    },
};
</script>

<style lang="scss" scoped>
.mobile-location-questions {
    .center-error-message {
        justify-content: center !important;
    }
}

.update-zip-text-link::before {
    content: "";
    display: inline-block;
    width: 13px;
    height: 16px;
    background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 13 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M6.49635 1.00142e-07C5.64734 -0.000153295 4.80722 0.175918 4.0274 0.517444C3.24757 0.858969 2.54443 1.35877 1.96099 1.98626C0.765713 3.27588 0.0999756 4.98141 0.0999756 6.75394C0.0999756 8.52646 0.765713 10.232 1.96099 11.5216L5.98324 15.777C6.04954 15.8475 6.12918 15.9036 6.21736 15.9419C6.30555 15.9802 6.40045 16 6.49635 16C6.59225 16 6.68716 15.9802 6.77534 15.9419C6.86353 15.9036 6.94317 15.8475 7.00946 15.777L11.0317 11.52C12.2391 10.2383 12.909 8.52914 12.8999 6.75394C12.9094 4.97818 12.2394 3.26832 11.0317 1.98626C10.4481 1.35899 9.74493 0.859347 8.96514 0.517839C8.18535 0.176331 7.34532 0.000130509 6.49635 1.00142e-07V1.00142e-07ZM6.49635 9.13131C6.02507 9.13131 5.56437 8.98913 5.17251 8.72275C4.78065 8.45637 4.47524 8.07776 4.29488 7.63479C4.11453 7.19181 4.06734 6.70438 4.15928 6.23412C4.25123 5.76387 4.47817 5.33191 4.81142 4.99287C5.14467 4.65384 5.56925 4.42295 6.03148 4.32941C6.49371 4.23587 6.97282 4.28388 7.40823 4.46736C7.84364 4.65085 8.21579 4.96157 8.47762 5.36023C8.73945 5.7589 8.87921 6.2276 8.87921 6.70707C8.87921 7.34974 8.62837 7.96611 8.18185 8.4207C7.73532 8.87528 7.12964 9.13088 6.49794 9.13131H6.49635Z' fill='%231574A1'/%3E%3C/svg%3E%0A");
    background-size: contain;
    vertical-align: middle;
    margin-right: 0.5em;
}

.address-questions {
    margin-top: 0em;
}

.update-mobile-location-text-link {
    white-space: pre-line;
}

.text-black {
    color: $black;
}
</style>
