<template>
  <DefaultSelect
    v-model="selected"
    v-bind="$attrs"
    clearable
    :options="options"
    :label
    :loading
  >
    <template #no-option>
      <q-item>
        <q-item-section class="text-grey">
          {{ $t("associado.no_approved_dependents") }}
        </q-item-section>
      </q-item>
    </template>
  </DefaultSelect>
</template>

<script setup>
import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { getDependentsByUser } from "src/api/profile";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

const { userId, label } = defineProps({
  userId: {
    type: Number,
    default: null,
  },
  label: {
    type: String,
    default: () => useI18n().t("associado.dependent"),
  },
});

const selected = defineModel({ type: Object });

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

const loadDependents = async (id) => {
  options.value = [];

  if (!id) return;

  loading.value = true;
  try {
    const dependents = await getDependentsByUser(id);
    options.value = dependents
      .filter((d) => d.status === "approved")
      .map((d) => ({ label: d.name, value: d.id, data: d }));
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

watch(
  () => userId,
  (id) => {
    selected.value = null;
    loadDependents(id);
  },
  { immediate: true },
);
</script>
