<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="value"
      :label="label"
      :error-messages="errorMessage"
      :name="name"
      :type="show ? 'text' : 'password'"
      :append-inner-icon="show ? 'mdi-eye' : 'mdi-eye-off'"
      autocomplete="section-blue one-time-code"
      @click:append-inner="show = !show"
    />
  </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";

const textField = ref(null);

const props = defineProps({
  name: {
    type: String,
    requird: 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,
    default: 0
  }
});

const show = ref(false);

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;
          }

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

const { value, errorMessage } = useField(fieldName, validationRules, {
  syncVModel: true
});
</script>
