<script lang="ts">
  import DataTable from '@components/admin/table/DataTable.svelte';
  import { deleteUser, editUser, type User, users } from '@app/admin/users/users.ts';
  import CrudPopup from '@components/admin/popup/CrudPopup.svelte';
  import { confirmPopupState } from '@components/popup/ConfirmPopup.ts';

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

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

  // callback
  function onUserDelete(user: User) {
    $confirmPopupState = {
      title: 'Nutzer löschen?',
      message: 'Soll der Nutzer wirklich gelöscht werden?',
      onConfirm: () => deleteUser(user)
    };
  }
</script>

<DataTable
  data={users}
  count={true}
  keys={[
    { key: 'firstname', label: 'Vorname', width: 15, sortable: true },
    { key: 'lastname', label: 'Nachname', width: 15, sortable: true },
    { key: 'birthday', label: 'Geburtstag', width: 5, sortable: true },
    { key: 'telephone', label: 'Telefon', width: 12, sortable: true },
    { key: 'username', label: 'Username', width: 20, sortable: true },
    { key: 'uuid', label: 'UUID', width: 23 }
  ]}
  onEdit={(user) => (editPopupUser = user)}
  onDelete={onUserDelete}
/>

<CrudPopup
  texts={{
    title: 'Nutzer bearbeiten',
    submitButtonTitle: 'Speichern',
    confirmPopupTitle: 'Änderungen speichern?',
    confirmPopupMessage: 'Sollen die Änderungen gespeichert werden?'
  }}
  target={editPopupUser}
  keys={[
    [
      { key: 'firstname', type: 'text', label: 'Vorname', options: { required: true } },
      { key: 'lastname', type: 'text', label: 'Nachname', options: { required: true } }
    ],
    [
      { key: 'birthday', type: 'date', label: 'Geburtstag', options: { required: true } },
      { key: 'telephone', type: 'tel', label: 'Telefonnummer' }
    ],
    [
      { key: 'username', type: 'text', label: 'Spielername', options: { required: true } },
      { key: 'uuid', type: 'text', label: 'UUID' }
    ]
  ]}
  onSubmit={editUser}
  bind:open={editPopupOpen}
/>
