<template>
  <q-select
    v-model="model"
    outlined
    :options="optionsRef"
    :label="label"
    :loading="isLoading"
    map-options
    emit-value
  >
    <template #no-option>
      <div class="q-pa-sm text-caption">
        Nenhum prestador vinculado a este serviço
      </div>
    </template>
  </q-select>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";

const { apiCall, label, loadWhen, noApiCall, options, loading } = defineProps({
  apiCall: {
    type: Function,
    required: false,
    default: null,
  },

  loadWhen: {
    type: [Boolean, String, Number],
    default: undefined,
  },

  noApiCall: {
    type: Boolean,
    default: false,
  },

  label: {
    type: String,
    default: "Selecione",
  },

  options: {
    type: Array,
    default: () => [],
  },

  loading: {
    type: Boolean,
    default: false,
  },
});

const model = defineModel();
const optionsRef = ref([]);
const isLoading = ref(loading);

const fetchOptions = async () => {
  if (noApiCall) {
    optionsRef.value = options;
    return;
  }

  if (!apiCall) return;

  try {
    isLoading.value = true;
    const response = await apiCall();
    optionsRef.value = response;
  } catch (error) {
    console.error("Falha ao buscar dados para o select:", error);
    optionsRef.value = [];
  } finally {
    isLoading.value = false;
  }
};

const canLoad = () => {
  if (loadWhen === undefined) return true;
  return !!loadWhen;
};

onMounted(async () => {
  if (loadWhen !== undefined) {
    if (!canLoad()) return;
  }
  await fetchOptions();
});

watch(
  () => loadWhen,
  async (newVal) => {
    if (newVal) {
      await fetchOptions();
    } else {
      optionsRef.value = [];
    }
  },
);
</script>
