<script lang="ts">
  import Badges from './Badges.svelte';
  import { Permissions } from '@util/permissions.ts';
  import type { Admin } from './types.ts';
  import CreateOrEditPopup from './CreateOrEditPopup.svelte';
  import { admins } from './state.ts';
  import Icon from '@iconify/svelte';
  import { editAdmin } from './actions.ts';

  // consts
  const availablePermissionBadges = {
    [Permissions.Admin.value]: 'Admin',
    [Permissions.Users.value]: 'Users',
    [Permissions.Reports.value]: 'Reports',
    [Permissions.Feedback.value]: 'Feedback',
    [Permissions.Settings.value]: 'Settings',
    [Permissions.Tools.value]: 'Tools'
  };

  // states
  let editAdminPopupAdmin = $state<Admin | null>(null);
</script>

<div class="h-screen overflow-x-auto">
  <table class="table table-pin-rows">
    <thead>
      <tr>
        <th style="width: 5%">#</th>
        <th style="width: 30%">Benutzername</th>
        <th style="width: 60%">Berechtigungen</th>
        <th style="width: 5%"></th>
      </tr>
    </thead>
    <tbody>
      {#each $admins as admin, i (admin)}
        <tr class="hover:bg-base-200">
          <td>{i + 1}</td>
          <td>{admin.username}</td>
          <td>
            <Badges available={availablePermissionBadges} set={new Permissions(admin.permissions).toNumberArray()} />
          </td>
          <td>
            <button class="cursor-pointer" onclick={() => (editAdminPopupAdmin = admin)}>
              <Icon icon="heroicons:pencil-square" />
            </button>
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
</div>

{#key editAdminPopupAdmin}
  <CreateOrEditPopup
    popupTitle="Admin bearbeiten"
    submitButtonTitle="Admin bearbeiten"
    confirmPopupTitle="Admin bearbeiten"
    confirmPopupMessage="Bist du sicher, dass du den Admin bearbeiten möchtest?"
    admin={editAdminPopupAdmin}
    open={editAdminPopupAdmin != null}
    onSubmit={editAdmin}
  />
{/key}
