<template>
  <DefaultSelect
    v-model="selectedGroup"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="filteredOptions"
    :loading="isLoading"
    :label
    @filter="filterFn"
  >
    <template #no-option>
      <q-item>
        <q-item-section class="text-grey">
          Nenhum grupo encontrado
        </q-item-section>
      </q-item>
    </template>
  </DefaultSelect>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { getGroupsForSelect } from "src/api/group";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

const { label } = defineProps({
  label: { type: String, default: "Grupo" },
});

// model value: { label, value, unit_ids } | null
const selectedGroup = defineModel({ type: Object });

const groupOptions = ref([]);
const filteredOptions = ref([]);
const isLoading = ref(true);

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

onMounted(async () => {
  try {
    const response = await getGroupsForSelect();
    groupOptions.value = response.map((g) => ({
      label: g.name,
      value: g.id,
      unit_ids: g.unit_ids ?? [],
    }));
    filteredOptions.value = groupOptions.value;
  } catch (error) {
    console.error("Failed to load groups:", error);
  } finally {
    isLoading.value = false;
  }
});
</script>
