<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"
      :rules="rules"
      autocomplete="section-blue one-time-code"
      maxLength="15"
    />
  </v-col>
</template>

<script lang="ts" setup>
import { MaybeRef, computed, ref } from "vue";
import { useField } from "vee-validate";
import { toTypedSchema } from "@vee-validate/zod";
import * as zod from "zod";
import { formatCPF, isValidCPF } from "@brazilian-utils/brazilian-utils";

const textField = ref(null);

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

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

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

const rules = computed(() => {
  return [
    (value: string) => value.length > 13 || "O CPF deve conter 11 dígitos"
  ];
});

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

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

const validationRules = computed<MaybeRef>(() => {
  if (!props.required) {
    return undefined;
  }

  return toTypedSchema(
    zod
      .string()
      .nonempty("Campo não pode ser vazio!")
      .refine(
        val => {
          if (props.min > 0) {
            return val.length >= props.min;
          }

          if (!isValidCPF(val)) {
            return "CPF inválido";
          }

          return true;
        },
        {
          message: `Campo deve ter no mínimo ${props.min} caracteres!`
        }
      )
  );
});

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