<template>
  <v-col
    ref="comp"
    :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-autocomplete
      v-bind="$attrs"
      v-model="value"
      :label="label"
      :error-messages="errorMessage"
      :name="name"
      :items="items"
      :readonly="loading"
      :clearable="clearable"
      :loading="loading"
      :return-object="false"
      :item-value="props.itemValue"
      :item-title="props.itemTitle"
      style="color: #070b41"
      validate-on="blur lazy"
      @blur="handleBlur"
    />
  </v-col>
</template>

<script lang="ts" setup>
import { useAxios } from "../../composables/useAxios";
import { useField, Form, Field } from "vee-validate";
import { toTypedSchema } from "@vee-validate/zod";
import * as zod from "zod";
import { MaybeRef, computed, nextTick, onMounted, ref, watch } from "vue";
const { $axios } = useAxios();

const props = defineProps({
  name: {
    type: String,
    requird: true
  },
  label: {
    type: String,
    required: true
  },
  modelValue: {
    type: Number || String || Object,
    required: true
  },
  clearable: {
    type: Boolean,
    default: true,
    required: false
  },
  endpoint: {
    type: String
  },
  itemValue: {
    type: String,
    default: "id"
  },
  itemTitle: {
    type: String,
    default: ""
  },
  autoSelectFirstAfterLoad: {
    type: Boolean,
    default: false
  },
  showFirstItemAsTodos: {
    type: Boolean,
    default: false
  },
  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 comp = ref(null);
const innerValue = ref(props.modelValue);

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

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, handleBlur, errorMessage, setValue, resetField } = useField(
  fieldName,
  validationRules,
  {
    //validateOnValueUpdate: false,
    syncVModel: true
  }
);

//setValue(props.modelValue);

// resetField({
//   value: props.modelValue,
//   touched: false,
//   errors: [],
// })

const loading = ref(false);
const items = ref([]);

const getItems = async () => {
  try {
    loading.value = true;

    let response = await $axios({
      url: props.endpoint,
      method: "GET"
    });

    items.value = response.data;

    if (props.showFirstItemAsTodos) {
      var todos = {};
      todos[props.itemTitle] = "Todos";
      todos[props.itemValue] = undefined;

      items.value.unshift(todos);
      emit("update:modelValue", items.value[0][props.itemValue]);
    }

    if (props.autoSelectFirstAfterLoad && items.value.length > 0) {
      nextTick(() => {
        //value = items.value[0][props.itemValue];
        emit("update:modelValue", items.value[0][props.itemValue]);
      });
    }
  } catch {
  } finally {
    loading.value = false;
  }
};

watch(
  () => props.endpoint,
  newValue => {
    getItems();
  }
);

// watch(value, (newX) => {
//   emit("update:modelValue", newX);
// });

onMounted(() => {
  getItems();
});
</script>
