<template>
  <v-col
    :cols="xs"
    :sm="sm || xs"
    :md="md || sm || xs"
    :lg="lg || md || sm || xs"
    :xl="xl || lg || md || sm || xs"
    :xxl="xxl || xl || lg || md || sm || xs"
    :class="$attrs.class + ' px-2'"
  >
    <v-text-field
      ref="textField"
      v-model="formattedValue"
      :label="label"
      :error-messages="errorMessage"
      :name="name"
      @keypress="onKeyPress"
      autocomplete="section-blue one-time-code"
      :rules="faxRules"
      maxLength="10"
    >
    </v-text-field>
  </v-col>
</template>

<script lang="ts" setup>
import { MaybeRef, computed, ref } from "vue";
import { useField } from "vee-validate";

const textField = ref(null);

const props = defineProps({
  name: {
    type: String,
    required: true
  },
  label: {
    type: String,
    required: true
  },
  modelValue: {
    type: String,
    required: true
  },
  xs: { type: String, default: "12" },
  sm: { type: String },
  md: { type: String },
  lg: { type: String },
  xl: { type: String },
  xxl: { type: String },
  required: {
    type: Boolean,
    default: false
  },
  min: {
    type: Number
  }
});

const faxRules = computed(() => {
  if (props.required) {
    return [
      (value: string) =>
        value.length === 9 ||
        value.length === 10 ||
        "O telefone Fax deve conter 8 ou 9 dígitos"
    ];
  }

  return undefined;
});

const formattedValue = computed({
  get: () => {
    return formatPhoneNumber(props.modelValue || "");
  },
  set: newValue => {
    const cleanedValue = newValue.replace(/\D/g, "");
    emit("update:modelValue", cleanedValue);
  }
});

const formatPhoneNumber = (phoneNumber: string) => {
  if (phoneNumber.length === 8) {
    return phoneNumber.replace(/(\d{4})(\d{4})/, "$1-$2");
  } else if (phoneNumber.length === 9) {
    return phoneNumber.replace(/(\d{5})(\d{4})/, "$1-$2");
  }
  return phoneNumber;
};

const onKeyPress = (event: any) => {
  if (event.key < "0" || event.key > "9") {
    event.preventDefault();
  }
};

const emit = defineEmits(["update:modelValue"]);

const fieldName = computed<MaybeRef>(() => {
  return props.name;
});

const { value, handleBlur, errorMessage, setValue, resetField } = useField<
  string
>(fieldName);
</script>
