<template>
  <DefaultSelect
    v-model="selectedService"
    v-bind="$attrs"
    :options="serviceOptions"
    :label
    :loading
    :placeholder
    :disable="!partnerAgreementId"
  >
    <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 { ref, watch } from "vue";
import { getServicesByPartner, getServicesByConvenio } from "src/api/partnerAgreementService";
import { useI18n } from "vue-i18n";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

const { label, placeholder, partnerAgreementId, forAssociado } = defineProps({
  label: {
    type: String,
    default: () => useI18n().t("associado.service"),
  },
  placeholder: {
    type: String,
    default: () => useI18n().t("common.actions.search"),
  },
  partnerAgreementId: {
    type: Number,
    default: null,
  },
  forAssociado: {
    type: Boolean,
    default: false,
  },
});

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

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

watch(
  () => partnerAgreementId,
  async (id) => {
    const savedSelection = selectedService.value;
    selectedService.value = null;
    serviceOptions.value = [];
    if (!id) return;
    loading.value = true;
    try {
      const services = await (forAssociado ? getServicesByConvenio(id) : getServicesByPartner(id));
      serviceOptions.value = services.map((s) => ({
        label: s.name,
        value: s.id,
        data: s,
      }));
      if (savedSelection?.value) {
        const match = serviceOptions.value.find((s) => s.value === savedSelection.value);
        if (match) selectedService.value = match;
      }
    } catch (e) {
      console.error(e);
    } finally {
      loading.value = false;
    }
  },
  { immediate: true },
);
</script>
