<script lang="ts">
  import BottomBar from './BottomBar.svelte';
  import SortableTr from '@components/admin/table/SortableTr.svelte';
  import SortableTh from '@components/admin/table/SortableTh.svelte';
  import { feedbacks } from './state.ts';
  import { fetchFeedbacks } from './actions.ts';
  import { onMount } from 'svelte';
  import type { Feedback } from './types.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 activeFeedback = $state<Feedback | null>(null);

  // lifecycle
  onMount(() => {
    fetchFeedbacks();
  });
</script>

<div class="min-h-[70vh] max-h-screen overflow-x-auto">
  <table class="table table-pin-rows">
    <thead>
      <SortableTr data={feedbacks}>
        <SortableTh style="width: 5%">#</SortableTh>
        <SortableTh style="width: 10%">Event</SortableTh>
        <SortableTh style="width: 20%" key="user.username">Nutzer</SortableTh>
        <SortableTh style="width: 20%" key="lastChanged">Datum</SortableTh>
        <SortableTh style="width: 45%">Inhalt</SortableTh>
      </SortableTr>
    </thead>
    <tbody>
      {#each $feedbacks as feedback, i (feedback.id)}
        <tr class="hover:bg-base-200" onclick={() => (activeFeedback = feedback)}>
          <td>{i + 1}</td>
          <td>{feedback.event}</td>
          <td>{feedback.user?.username}</td>
          <td>{dateFormat.format(new Date(feedback.lastChanged))}</td>
          <td>{feedback.content}</td>
        </tr>
      {/each}
    </tbody>
  </table>
</div>

<BottomBar feedback={activeFeedback} />
