<script lang="ts">
  import { teams } from './state.ts';
  import type { Team } from './types.ts';
  import { editTeam } from './actions.ts';
  import Icon from '@iconify/svelte';
  import SortableTr from '@components/admin/table/SortableTr.svelte';
  import SortableTh from '@components/admin/table/SortableTh.svelte';
  import CreateOrEditPopup from '@app/admin/teams/CreateOrEditPopup.svelte';

  // state
  let editTeamPopupTeam = $state<Team | null>(null);
</script>

<div class="h-screen overflow-x-auto">
  <table class="table table-pin-rows">
    <thead>
      <SortableTr data={teams}>
        <SortableTh style="width: 5%">#</SortableTh>
        <SortableTh style="width: 5%">Farbe</SortableTh>
        <SortableTh style="width: 25%" key="name">Name</SortableTh>
        <SortableTh style="width: 30%" key="memberOne.username">Spieler 1</SortableTh>
        <SortableTh style="width: 30%" key="memberTwo.username">Spieler 2</SortableTh>
        <SortableTh style="width: 5%"></SortableTh>
      </SortableTr>
    </thead>
    <tbody>
      {#each $teams as team, i (team.id)}
        <tr class="hover:bg-base-200">
          <td>{i + 1}</td>
          <td>
            <div class="rounded-sm w-3 h-3" style="background-color: {team.color}"></div>
          </td>
          <td>{team.name}</td>
          {#if team.memberOne.id != null}
            <td>{team.memberOne.username}</td>
          {:else}
            <td class="text-base-content/30">{team.memberOne.username}</td>
          {/if}
          {#if team.memberTwo.id != null}
            <td>{team.memberTwo.username}</td>
          {:else}
            <td class="text-base-content/30">{team.memberTwo.username}</td>
          {/if}
          <td>
            <button class="cursor-pointer" onclick={() => (editTeamPopupTeam = team)}>
              <Icon icon="heroicons:pencil-square" />
            </button>
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
</div>

{#key editTeamPopupTeam}
  <CreateOrEditPopup
    popupTitle="Team bearbeiten"
    submitButtonTitle="Team bearbeiten"
    confirmPopupTitle="Team bearbeiten"
    confirmPopupMessage="Bist du sicher, dass du das Team bearbeiten möchtest?"
    team={editTeamPopupTeam}
    open={editTeamPopupTeam != null}
    onSubmit={editTeam}
  />
{/key}
