<script lang="ts">
  import { addTeam, deleteTeam, type Team, teams } from '@app/admin/teams/teams.ts';
  import DataTable from '@components/admin/table/DataTable.svelte';
  import CrudPopup from '@components/admin/popup/CrudPopup.svelte';
  import { confirmPopupState } from '@components/popup/ConfirmPopup.ts';

  // state
  let editPopupTeam = $state(null);
  let editPopupOpen = $derived(!!editPopupTeam);

  // lifecycle
  $effect(() => {
    if (!editPopupOpen) editPopupTeam = null;
  });

  // callback
  function onTeamDelete(team: Team) {
    $confirmPopupState = {
      title: 'Team löschen?',
      message: 'Soll das Team wirklich gelöscht werden?',
      onConfirm: () => deleteTeam(team)
    };
  }
</script>

{#snippet color(value: string)}
  <div class="rounded-sm w-3 h-3" style="background-color: {value}"></div>
{/snippet}

<DataTable
  data={teams}
  count={true}
  keys={[
    { key: 'color', label: 'Farbe', width: 5, transform: color },
    { key: 'name', label: 'Name', width: 25 },
    { key: 'memberOne.username', label: 'Spieler 1', width: 30 },
    { key: 'memberTwo.username', label: 'Spieler 2', width: 30 }
  ]}
  onEdit={(team) => (editPopupTeam = team)}
  onDelete={onTeamDelete}
/>

<CrudPopup
  texts={{
    title: 'Team bearbeiten',
    submitButtonTitle: 'Speichern',
    confirmPopupTitle: 'Änderungen speichern?',
    confirmPopupMessage: 'Sollen die Änderungen gespeichert werden?'
  }}
  target={editPopupTeam}
  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',
        options: { required: true, validate: (user) => !!user.username }
      },
      {
        key: 'memberTwo',
        type: 'user-search',
        label: 'Spieler 2',
        default: { id: null, username: null },
        options: { required: true, validate: (user) => !!user.username }
      }
    ],
    [
      {
        key: 'lastJoined',
        type: 'datetime-local',
        label: 'Zuletzt gejoined',
        default: { id: null, username: null },
        options: { convert: (date) => (date ? date : null) }
      }
    ]
  ]}
  onSubmit={addTeam}
  bind:open={editPopupOpen}
/>
