<template>
  <DefaultSelect
    v-model="selectedUnit"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="filteredOptions"
    :loading="isLoading"
    :placeholder
    :label
    @filter="filterFn"
  >
    <template #no-option>
      <q-item>
        <q-item-section class="text-grey">
          {{ $t("http.errors.no_records_found") }}
        </q-item-section>
      </q-item>
    </template>
  </DefaultSelect>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { getUnitsForSelect } from "src/api/unit";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import { formatUnitName } from "src/helpers/utils";

const { placeholder, label, initialId } = defineProps({
  placeholder: { type: String, default: "Buscar unidade" },
  label: { type: String, default: "Unidade" },
  initialId: { type: Number, default: null },
});

const selectedUnit = defineModel({ type: Object });
const unitOptions = ref([]);
const filteredOptions = ref([]);
const isLoading = ref(true);

const selectUnitById = (id) => {
  selectedUnit.value = unitOptions.value.find((o) => o.value === id) ?? null;
};

const filterFn = (val, update) => {
  update(() => {
    if (val === "") {
      filteredOptions.value = unitOptions.value;
    } else {
      const needle = val.toLowerCase();
      filteredOptions.value = unitOptions.value.filter((v) =>
        v.label.toLowerCase().includes(needle),
      );
    }
  });
};

onMounted(async () => {
  try {
    const response = await getUnitsForSelect();
    unitOptions.value = response.map((unit) => ({
      label: formatUnitName(unit),
      value: unit.id,
    }));
    filteredOptions.value = unitOptions.value;
    if (initialId) selectUnitById(initialId);
  } catch (error) {
    console.error("Failed to load units:", error);
  } finally {
    isLoading.value = false;
  }
});

watch(
  () => initialId,
  (newId) => {
    if (newId && unitOptions.value.length > 0) {
      selectUnitById(newId);
    }
  },
);

defineExpose({ selectUnitById });
</script>
