<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card style="width: 480px; max-width: 95vw">
      <DefaultDialogHeader
        :title="() => $t('loja.interested_in') + ': ' + storeItemName"
        @close="onDialogCancel"
      />

      <q-card-section>
        <div v-if="loading" class="flex flex-center q-py-md">
          <q-spinner color="primary" size="32px" />
        </div>

        <div v-else-if="interests.length === 0" class="text-center text-grey q-py-md">
          {{ $t('http.errors.no_records_found') }}
        </div>

        <q-list v-else separator>
          <q-item v-for="person in interests" :key="person.id">
            <q-item-section avatar>
              <q-avatar color="purple-8" text-color="white" size="36px">
                {{ initials(person.name) }}
              </q-avatar>
            </q-item-section>
            <q-item-section>
              <q-item-label>{{ person.name }}</q-item-label>
              <q-item-label caption>{{ person.email }}</q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useQuasar, useDialogPluginComponent } from "quasar";
import { useI18n } from "vue-i18n";
import { getStoreItemInterests } from "src/api/storeItem";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";

defineEmits([...useDialogPluginComponent.emits]);

const props = defineProps({
  storeItemId:   { type: Number, required: true },
  storeItemName: { type: String, default: "" },
});

const $q = useQuasar();
const { t } = useI18n();
const { dialogRef, onDialogHide, onDialogCancel } = useDialogPluginComponent();

const loading = ref(true);
const interests = ref([]);

const initials = (name) => {
  if (!name) return "?";
  return name.split(" ").slice(0, 2).map((w) => w[0]).join("").toUpperCase();
};

onMounted(async () => {
  try {
    interests.value = await getStoreItemInterests(props.storeItemId);
  } catch {
    $q.notify({ type: "negative", message: t("http.errors.failed") });
  } finally {
    loading.value = false;
  }
});
</script>
