<template>
    <div class="scheduling-zip-search mt-4">
        <label for="sz-service-zip" v-html="zipLabelText"></label>
        <div class="scheduling-zip-search__input-wrapper">
            <input
                id="sz-service-zip"
                ref="zipInput"
                class="scheduling-zip-search__input"
                :class="{ 'has-error': hasError }"
                type="text"
                name="sz-service-zip"
                :value="localZipCode"
                :disabled="disabled"
                @input="onZipInput"
                @keydown.enter="onZipSearch" />
            <button
                class="scheduling-zip-search__search-button"
                type="button"
                aria-label="Search"
                :disabled="disabled"
                @click="onZipSearch" />
        </div>
        <span class="scheduling-zip-search__error" :class="{ active: hasError }">
            {{ errorMessage }}
        </span>
    </div>
</template>

<script>
import store from "@/store";
import { storeActions } from "@/constants/store-actions";
import { defineRule, validate } from "vee-validate";
import { required, regex } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import {
    getBillToAccountNumber,
    getZipCodeData,
} from "@/layouts/service-location/helpers/service-location-helper/service-location-helper";

defineRule("zip-required", required(errorMessages.SERVICE_ZIP_REQUIRED));
defineRule("zip-format", regex(/(^\d{5}$)|(^\d{5}-\d{4}$)/, errorMessages.SERVICE_ZIP_FORMAT));

const ZIP_VALIDATION_RULES = "zip-required|zip-format";

export default {
    name: "schedulingZipSearch",
    emits: ["update:modelValue", "zip-searched"],
    props: {
        modelValue: {
            type: String,
            default: "",
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        pageNameToLog: {
            type: String,
            default: null,
        },
    },
    data() {
        return {
            errorMessage: "",
        };
    },
    computed: {
        hasError() {
            return Boolean(this.errorMessage);
        },
        zipLabelText() {
            return this.getCmsContent("ServiceZipQuestionWidget", "QuestionText");
        },
        localZipCode: {
            get() {
                return this.modelValue;
            },
            set(value) {
                this.$emit("update:modelValue", value);
            },
        },
    },
    methods: {
        onZipInput(event) {
            const digitsOnly = event.target.value.replace(/\D/g, "").slice(0, 5);
            event.target.value = digitsOnly;
            this.localZipCode = digitsOnly;
            this.errorMessage = "";
        },
        focusZipInput() {
            const zipInput = this.$refs.zipInput;
            if (!zipInput) {
                return;
            }

            zipInput.scrollIntoView({ behavior: "smooth", block: "center" });
            zipInput.focus({ preventScroll: true });
        },
        async onZipSearch(event) {
            event?.preventDefault?.();

            if (this.disabled) {
                return;
            }

            const validationResult = await validate(this.localZipCode, ZIP_VALIDATION_RULES);
            if (!validationResult.valid) {
                this.errorMessage = validationResult.errors[0] ?? "";
                this.$refs.zipInput?.focus();
                return;
            }

            this.errorMessage = "";

            const zipCodeData = await getZipCodeData(this.localZipCode, this.pageNameToLog);
            await store.dispatch(storeActions.SAVE_SERVICE_ZIP_CODE_INFO, {
                zipCode: this.localZipCode,
                state: zipCodeData.state,
                zipCodeCtu: zipCodeData.zipCodeCtu,
            });
            const billToAccountNumber = await getBillToAccountNumber(
                zipCodeData.zipCodeCtu,
                this.pageNameToLog
            );

            this.$emit("zip-searched", {
                zipCode: this.localZipCode,
                billToAccountNumber,
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.scheduling-zip-search {
    label {
        display: flex;
        margin-bottom: 0.5rem;
        font-weight: 600;
    }

    &__input-wrapper {
        position: relative;
    }

    &__input {
        height: 48px;
        width: 100%;
        border-radius: 50rem;
        border: none;
        outline: 1px solid $gray-300;
        box-shadow: 0px 1px 4px 0 rgba(0, 0, 0, 0.2);
        color: $gray-650;
        font-weight: 400;
        padding-left: 1rem;
        padding-right: 3.5rem;

        &:focus {
            outline: 2px solid #0070d1;
            border: none;
        }

        &.has-error {
            outline: 2px solid $red;
        }
    }

    &__search-button {
        position: absolute;
        top: 0;
        right: 0;
        height: 48px;
        border-radius: 0 50rem 50rem 0;
        width: 50px;
        border: none;
        background-color: $blue-150;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M15.7816 14.733L11.825 10.7765C12.8831 9.4503 13.3934 7.76935 13.2512 6.07874C13.1089 4.38812 12.3248 2.81612 11.0599 1.68544C9.79496 0.554768 8.1452 -0.0487819 6.44927 -0.0013033C4.75335 0.0461753 3.13993 0.74108 1.94026 1.94075C0.740592 3.14042 0.045687 4.75384 -0.00179158 6.44976C-0.0492702 8.14569 0.55428 9.79545 1.68495 11.0604C2.81563 12.3253 4.38763 13.1094 6.07825 13.2516C7.76886 13.3939 9.44981 12.8836 10.776 11.8255L14.7347 15.7842C14.8042 15.8529 14.8867 15.9073 14.9773 15.9442C15.0678 15.981 15.1648 15.9997 15.2626 15.9991C15.3604 15.9985 15.4571 15.9787 15.5473 15.9407C15.6374 15.9027 15.7192 15.8474 15.7879 15.7778C15.8567 15.7082 15.911 15.6258 15.9479 15.5352C15.9848 15.4446 16.0035 15.3477 16.0029 15.2499C16.0023 15.1521 15.9824 15.0553 15.9445 14.9652C15.9065 14.8751 15.8511 14.7933 15.7816 14.7246V14.733ZM6.63719 11.7916C5.61784 11.7916 4.62139 11.4893 3.77383 10.923C2.92628 10.3567 2.26569 9.55175 1.8756 8.60999C1.48551 7.66824 1.38345 6.63196 1.58231 5.6322C1.78118 4.63244 2.27204 3.7141 2.99283 2.99332C3.71361 2.27253 4.63195 1.78167 5.63171 1.5828C6.63147 1.38394 7.66775 1.486 8.6095 1.87609C9.55126 2.26618 10.3562 2.92677 10.9225 3.77432C11.4888 4.62188 11.7911 5.61833 11.7911 6.63768C11.7894 8.00406 11.2459 9.314 10.2797 10.2802C9.31351 11.2464 8.00357 11.7899 6.63719 11.7916Z' fill='%230070D1'/%3E%3C/svg%3E%0A");
        background-repeat: no-repeat;
        background-position: center;

        &:disabled {
            cursor: not-allowed;
            opacity: 0.6;
        }
    }

    &__error {
        color: $red;
        font-size: 0.875rem;
        margin-top: 0.25rem;
        display: flex;
        max-height: 0;
        overflow: hidden;

        &.active {
            max-height: 25px;
            transition: max-height 0.3s ease-in-out;
        }
    }
}
</style>
