<script lang="ts">
  import Input from '@components/input/Input.svelte';
  import CrudPopup from '@components/admin/popup/CrudPopup.svelte';
  import { addUser, fetchUsers } from '@app/admin/users/users.ts';

  // states
  let usernameFilter = $state<string | null>(null);

  let createPopupOpen = $state(false);

  // lifecycle
  $effect(() => {
    fetchUsers({ username: usernameFilter });
  });
</script>

<div>
  <fieldset class="fieldset border border-base-content/50 rounded-box p-2">
    <legend class="fieldset-legend">Filter</legend>
    <Input bind:value={usernameFilter} label="Username" />
  </fieldset>
  <div class="divider my-1"></div>
  <button class="btn btn-soft w-full" onclick={() => (createPopupOpen = true)}>
    <span class="iconify iconify-[heroicons--plus-16-solid]"></span>
    <span>Neuer Nutzer</span>
  </button>
</div>

<CrudPopup
  texts={{
    title: 'Nutzer erstellen',
    submitButtonTitle: 'Erstellen',
    confirmPopupTitle: 'Nutzer erstellen?',
    confirmPopupMessage: 'Soll der neue Nutzer erstellt werden?'
  }}
  target={null}
  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', default: null }
    ],
    [
      { key: 'username', type: 'text', label: 'Spielername', options: { required: true } },
      {
        key: 'edition',
        type: 'select',
        label: 'Edition',
        options: { values: { java: 'Java', bedrock: 'Bedrock' }, required: true }
      }
    ],
    [{ key: 'uuid', type: 'text', label: 'UUID', default: null, options: { dynamicWidth: true } }]
  ]}
  onSubmit={addUser}
  bind:open={createPopupOpen}
/>
