<script lang="ts">
  import BitBadge from '@components/input/BitBadge.svelte';
  import { Permissions } from '@util/permissions.ts';
  import { type Admin, admins, deleteAdmin, editAdmin } from '@app/admin/admins/admins.ts';
  import CrudPopup from '@components/admin/popup/CrudPopup.svelte';
  import DataTable from '@components/admin/table/DataTable.svelte';
  import { confirmPopupState } from '@components/popup/ConfirmPopup.ts';

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

  // callback
  function onAdminDelete(admin: Admin) {
    $confirmPopupState = {
      title: 'Admin löschen',
      message: 'Soll der Admin wirklich gelöscht werden?',
      onConfirm: () => deleteAdmin(admin)
    };
  }
</script>

{#snippet permissionsBadge(permissions: number)}
  <BitBadge available={Permissions.asOptions()} value={permissions} readonly />
{/snippet}

<DataTable
  data={admins}
  count={true}
  keys={[
    { key: 'username', label: 'Username', width: 30 },
    { key: 'permissions', label: 'Berechtigungen', width: 60, transform: permissionsBadge }
  ]}
  onEdit={(admin) => (editPopupAdmin = admin)}
  onDelete={onAdminDelete}
/>

<CrudPopup
  texts={{
    title: 'Admin bearbeiten',
    submitButtonTitle: 'Speichern',
    confirmPopupTitle: 'Änderungen speichern',
    confirmPopupMessage: 'Sollen die Änderungen gespeichert werden?'
  }}
  target={editPopupAdmin}
  keys={[
    [
      { key: 'username', type: 'text', label: 'Username', options: { required: true } },
      { key: 'password', type: 'password', label: 'Passwort', default: null, options: { convert: (v) => v || null } }
    ],
    [
      {
        key: 'permissions',
        type: 'bit-badge',
        label: 'Berechtigungen',
        default: 0,
        options: { available: Permissions.asOptions() }
      }
    ]
  ]}
  onSubmit={editAdmin}
  bind:open={editPopupOpen}
/>
