<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-combobox
      v-bind="$attrs"
      v-model="innerValue"
      :label="label"
      :error-messages="errorMessage"
      :name="name"
      :items="items"
      :readonly="loading"
      :clearable="clearable"
      :loading="loading"
      :return-object="false"
      :item-value="props.itemValue"
      style="color: #070b41"
      @update:modelValue="emit('update:modelValue', innerValue)"
    ></v-combobox>
  </v-col>
</template>

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

const props = defineProps({
  name: {
    type: String,
    requird: true
  },
  label: {
    type: String,
    required: true
  },
  modelValue: {
    type: String,
    required: true
  },
  clearable: {
    type: Boolean,
    default: true,
    required: false
  },
  endpoint: {
    type: String
  },
  itemValue: {
    type: String,
    default: "id"
  },
  autoSelectFirstAfterLoad: {
    type: Boolean,
    default: false
  },
  xs: { type: String, default: 12 },
  sm: { type: String },
  md: { type: String },
  lg: { type: String },
  xl: { type: String },
  xxl: { type: String }
});

const innerValue = ref(null);

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

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

const validationRules = computed<MaybeRef>(() => {
  return toTypedSchema(zod.string().default(props.modelValue));
});

const { value, handleBlur, errorMessage, setValue } = useField(
  fieldName,
  validationRules
);

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.autoSelectFirstAfterLoad && items.value.length > 0) {
      nextTick(() => {
        innerValue.value = items.value[0][props.itemValue];
        emit("update:modelValue", items.value[0][props.itemValue]);
      });
    }
  } catch {
  } finally {
    loading.value = false;
  }
};

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

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