<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="dddRules"
      maxLength="2"
    />
  </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 dddRules = computed(() => {
  if (props.required) {
    return [
      (value: string) => value.length === 2 || "O DDD deve conter 2 dígitos"
    ];
  }
  return undefined;
});

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

const formattedValue = computed({
  get: () => {
    return props.modelValue || "";
  },
  set: newValue => {
    emit("update:modelValue", newValue);
  }
});

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

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

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