<script lang="ts">
  import BottomBar from '@app/admin/reports/BottomBar.svelte';
  import { onMount, untrack } from 'svelte';
  import DataTable from '@components/admin/table/DataTable.svelte';
  import { type StrikeReasons, getStrikeReasons, reports } from '@app/admin/reports/reports.ts';

  // consts
  const dateFormat = new Intl.DateTimeFormat('de-DE', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });

  // states
  let strikeReasons = $state<StrikeReasons>([]);
  let activeReport = $state<Report | null>(null);

  // lifecycle
  onMount(() => {
    getStrikeReasons().then((data) => (strikeReasons = data ?? []));
  });

  let initialSort = false;
  $effect(() => {
    if ($reports.length == 0 || initialSort) return;
    initialSort = true;

    $reports = $reports.toSorted(
      (a, b) =>
        [null, 'open', 'closed'].indexOf(a.status?.status ?? null) -
        [null, 'open', 'closed'].indexOf(b.status?.status ?? null)
    );
  });
</script>

{#snippet date(value: string)}
  {value ? dateFormat.format(new Date(value)) : ''}
{/snippet}

{#snippet status(value: null | 'open' | 'closed')}
  {#if value === 'open'}
    <p>In Bearbeitung</p>
  {:else if value === 'closed'}
    <p>Bearbeitet</p>
  {:else if value === null}
    <p>Unbearbeitet</p>
  {/if}
{/snippet}

<div class="h-screen flex flex-col justify-between">
  <DataTable
    data={reports}
    count={true}
    keys={[
      { key: 'reason', label: 'Grund', width: 35 },
      { key: 'reporter.username', label: 'Report Ersteller', width: 15 },
      { key: 'reported.username', label: 'Reporteter Spieler', width: 15 },
      { key: 'createdAt', label: 'Datum', width: 15, sortable: true, transform: date },
      { key: 'status.status', label: 'Bearbeitungsstatus', width: 10, sortable: true, transform: status }
    ]}
    onClick={(report) => (activeReport = report)}
  />

  {#key activeReport}
    <BottomBar {strikeReasons} report={activeReport} />
  {/key}
</div>
