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

  // types
  interface Props {
    adversary: string | null;
  }

  // input
  const { adversary }: Props = $props();

  // states
  let reportTarget = $state<'player' | 'unknown'>(adversary ? 'player' : 'unknown');
  let adversaryUsername = $state(adversary);

  // lifecycle
  $effect(() => {
    dispatchAdversaryInput(adversaryUsername);
  });

  // functions
  async function getSuggestions(query: string, _limit: number) {
    const { data, error } = await actions.report.usernames({ username: query });

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

    return data.usernames.map((u) => ({ name: u, value: u }));
  }

  function dispatchAdversaryInput(username: string | null) {
    document.dispatchEvent(
      new CustomEvent('adversaryInput', {
        detail: {
          adversaryUsername: username
        }
      })
    );
  }
</script>

<div class="flex justify-center gap-4">
  <Select
    bind:value={
      () => reportTarget,
      (v) => {
        dispatchAdversaryInput(v === 'player' ? adversaryUsername : null);
        reportTarget = v;
      }
    }
    values={{
      player: 'Ich möchte einen bestimmten Spieler reporten',
      unknown: 'Ich möchte einen unbekannten Spieler reporten'
    }}
    dynamicWidth
  />

  {#if reportTarget === 'player'}
    <Search
      value={adversaryUsername}
      requestSuggestions={getSuggestions}
      onSubmit={(value) => (adversaryUsername = value != null ? value.value : null)}
    />
  {/if}
</div>
