<script setup>
import { computed } from "vue";
import pluralize from "pluralize";
import { useNctHeaders, useFetch } from "#imports";
import { useRuntimeConfig } from "#app";
const props = defineProps({
  modelValue: { type: [String, Number, null], required: true },
  fieldName: { type: String, required: false },
  tableName: { type: String, required: false }
});
const emit = defineEmits(["update:modelValue"]);
let urlPath = "";
if (props.tableName) {
  urlPath = props.tableName;
} else if (props.fieldName) {
  const baseName = props.fieldName.replace(/(_id|Id)$/, "");
  urlPath = pluralize(baseName);
}
const { apiBase } = useRuntimeConfig().public.crudTable;
const { data: options } = await useFetch(() => `${apiBase}/${urlPath}`, {
  key: `crud-${urlPath}`,
  transform: (rows) => rows?.map((row) => {
    const r = row;
    return {
      label: r.name || r.title || r.num || `#${r.id}`,
      value: r.id,
      extra: r.email
    };
  }),
  lazy: true,
  headers: useNctHeaders()
});
const selected = computed({
  get: () => options.value?.find((opt) => opt.value == props.modelValue),
  set: (val) => {
    emit("update:modelValue", val?.value);
  }
});
</script>

<template>
  <USelectMenu
    v-model="selected"
    :items="options || []"
    option-attribute="label"
    placeholder="Select"
    class="w-full"
  >
    <template #item-label="{ item }">
      <span>{{ item.label }}</span>
      <span
        v-if="item.extra"
        class="text-gray-400 text-xs ml-2"
      >({{ item.extra }})</span>
    </template>
  </USelectMenu>
</template>
