<script setup lang="ts">
import { useFetch, createError } from '#app';

const props = defineProps<{
  label?: string,
  optional?: boolean,
  modelValue?: `${bigint}`,
}>();

// eslint-disable-next-line func-call-spacing
const emit = defineEmits<{
  (e: "update:modelValue", value: `${bigint}`): void,
}>();

// FIXME: allow to search all clients instead of newest 50 (needs api call)
const clientsRequest = await useFetch("/api/clients");
if (clientsRequest.error.value) throw createError(clientsRequest.error.value?.data ?? "");
const clients = clientsRequest.data.value?.map((e) => {
  return {
    value: e.id,
    title: e.name ?? `[null] (${e.id})`,
    props: {
      subtitle: e.address,
    },
  };
}) ?? [];
</script>

<template>
  <v-autocomplete
    :label="label ?? 'Client'"
    :model-value="modelValue"
    :items="clients"
    :clearable="optional"
    @update:model-value="v => emit('update:modelValue', v)"
  />
</template>
