<template>
    <textboxQuestion
        ref="zipInputTextQuestion"
        v-model="internalZipcode"
        :cmsWidgetName="cmsWidgetName"
        inputId="serviceZipCode"
        cornerStyle="rounded"
        mask="#####"
        isRequired
        :hasError="hasError"
        :validationRules="`zip-required|${cmsWidgetName}-zip-format`"
        @clickEvent="updateModelValue" />
</template>

<script>
import textboxQuestion from '@/digital-components/textbox-question/textbox-question.vue';

// Supporting Files
import { defineRule } from 'vee-validate';
import { required, regex } from '@/helpers/validation-rules';
import errorMessages from '@/constants/error-messages';

// Define Validation Rules
defineRule('zip-required', required(errorMessages.SERVICE_ZIP_REQUIRED));

export default {
    name: 'service-zip-question',
    components: {
        textboxQuestion
    },
    // TODO: Correct prop def.
    props: {
        modelValue: String,
        cmsWidgetName: String,
        serviceZipFormatErrorMessage: {
            type: String,
            default: errorMessages.SERVICE_ZIP_FORMAT
        },
        hasError: {
            type: Boolean,
            default: false
        }
    },
    emits: ['update:modelValue'],
    data() {
        return {
            internalZipcode: this.modelValue
        };
    },
    watch: {
        modelValue(newValue) {
            if (newValue !== this.internalZipcode) {
                this.internalZipcode = newValue;
            }
        }
    },
    mounted() {
        defineRule(`${this.cmsWidgetName}-zip-format`, regex(/^\d{5}$/, this.serviceZipFormatErrorMessage));
    },
    methods: {
        updateModelValue() {
            this.$emit('update:modelValue', this.internalZipcode);
        }
    }
};
</script>
<style lang="scss" scoped>
    .textbox-question.has-success {
        :deep(input.form-control) {
            border: $border-input;
            &:focus {
                border: $border-input-focus;
            }
        }
    }
</style>
