<script lang="ts">
  import Input from '@components/input/Input.svelte';
  import Icon from '@iconify/svelte';
  import CrudPopup from '@components/admin/popup/CrudPopup.svelte';
  import { addTeam, fetchTeams } from '@app/admin/teams/teams.ts';

  // states
  let teamNameFilter = $state<string | null>(null);
  let memberUsernameFilter = $state<string | null>(null);

  let createPopupOpen = $state(false);

  // lifecycle
  $effect(() => {
    fetchTeams(teamNameFilter, memberUsernameFilter);
  });
</script>

<div>
  <fieldset class="fieldset border border-base-content/50 rounded-box p-2">
    <legend class="fieldset-legend">Filter</legend>
    <Input bind:value={teamNameFilter} label="Team Name" />
    <Input bind:value={memberUsernameFilter} label="Spieler Username" />
  </fieldset>
  <div class="divider my-1"></div>
  <button class="btn btn-soft w-full" onclick={() => (createPopupOpen = true)}>
    <Icon icon="heroicons:plus-16-solid" />
    <span>Neues Team</span>
  </button>
</div>

<CrudPopup
  texts={{
    title: 'Team erstellen',
    submitButtonTitle: 'Erstellen',
    confirmPopupTitle: 'Team erstellen?',
    confirmPopupMessage: 'Sollen das neue Team erstellt werden?'
  }}
  target={null}
  keys={[
    [
      { key: 'name', type: 'text', label: 'Name', options: { required: true } },
      { key: 'color', type: 'color', label: 'Farbe', options: { required: true } }
    ],
    [
      {
        key: 'memberOne',
        type: 'user-search',
        label: 'Spieler 1',
        default: { id: null, username: '' },
        options: { required: true, validate: (user) => !!user.username }
      },
      {
        key: 'memberTwo',
        type: 'user-search',
        label: 'Spieler 2',
        default: { id: null, username: '' },
        options: { required: true, validate: (user) => !!user.username }
      }
    ],
    [
      {
        key: 'lastJoined',
        type: 'datetime-local',
        label: 'Zuletzt gejoined',
        default: null,
        options: { convert: (date) => (date ? date : null) }
      }
    ]
  ]}
  onSubmit={addTeam}
  bind:open={createPopupOpen}
/>
