<script lang="ts">
  import { type ActionReturnType, actions } from 'astro:actions';
  import Search from '@components/admin/search/Search.svelte';
  import { actionErrorPopup } from '@util/action.ts';

  // types
  type Users = Exclude<ActionReturnType<typeof actions.user.users>['data'], undefined>['users'];
  type User = Users[0];
  interface Props {
    id?: string;
    value?: string | null;
    label?: string;
    readonly?: boolean;
    required?: boolean;
    mustMatch?: boolean;

    onSubmit?: (user: User | null) => void;
  }

  // inputs
  let { id, value = $bindable(), label, readonly, required, mustMatch, onSubmit }: Props = $props();

  // functions
  async function getSuggestions(query: string, limit: number) {
    const { data, error } = await actions.user.users({
      username: query,
      limit: limit
    });

    if (error) {
      actionErrorPopup(error);
      return [];
    }

    return data.users.map((user) => ({ name: user.username, value: user }));
  }
</script>

<Search
  {id}
  bind:value
  {label}
  {readonly}
  {required}
  {mustMatch}
  requestSuggestions={async (username) => getSuggestions(username, 5)}
  onSubmit={async (suggestion) => onSubmit?.(suggestion != null ? suggestion.value : null)}
/>
