<script lang="ts">
  import Input from '@components/input/Input.svelte';
  import CrudPopup from '@components/admin/popup/CrudPopup.svelte';
  import { addReport, fetchReports } from '@app/admin/reports/reports.ts';
  import Checkbox from '@components/input/Checkbox.svelte';

  // states
  let showDrafts = $state(false);
  let reporterUsernameFilter = $state<string | null>(null);
  let reportedUsernameFilter = $state<string | null>(null);

  let createPopupOpen = $state(false);

  // lifecycle
  $effect(() => {
    fetchReports(reporterUsernameFilter, reportedUsernameFilter, showDrafts);
  });
</script>

<div>
  <fieldset class="fieldset border border-base-content/50 rounded-box p-2">
    <legend class="fieldset-legend">Filter</legend>
    <Checkbox bind:checked={showDrafts} label="Entwürfe zeigen" />
    <Input bind:value={reporterUsernameFilter} label="Reporter Ersteller" />
    <Input bind:value={reportedUsernameFilter} label="Reporteter Spieler" />
  </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 Report</span>
  </button>
</div>

<CrudPopup
  texts={{
    title: 'Report erstellen',
    submitButtonTitle: 'Erstellen',
    confirmPopupTitle: 'Report erstellen?',
    confirmPopupMessage: 'Soll der Report erstellt werden?'
  }}
  target={null}
  keys={[
    [
      {
        key: 'reporter',
        type: 'user-search',
        label: 'Report Ersteller',
        default: { id: null, username: null },
        options: { required: true, mustMatch: true, validate: (user) => user?.id != null }
      },
      {
        key: 'reported',
        type: 'user-search',
        label: 'Reporteter Spieler',
        options: { mustMatch: true, validate: (user) => user?.id != null }
      }
    ],
    [
      {
        key: 'reason',
        type: 'text',
        label: 'Grund',
        options: { required: true, dynamicWidth: true, validate: (reason) => reason }
      }
    ],
    [{ key: 'body', type: 'textarea', label: 'Inhalt', default: null, options: { rows: 5, dynamicWidth: true } }],
    [
      {
        key: 'createdAt',
        type: 'checkbox',
        label: 'Report kann bearbeitet werden',
        default: true,
        options: { convert: (v) => (v ? null : new Date().toISOString()) }
      }
    ]
  ]}
  onSubmit={addReport}
  bind:open={createPopupOpen}
/>
