---
import WebsiteLayout from '@layouts/website/WebsiteLayout.astro';
import Input from '@components/input/Input.svelte';
import Textarea from '@components/input/Textarea.svelte';
import { db } from '@db/database.ts';

const { urlHash } = Astro.params;

const feedback = urlHash ? await db.getFeedbackByUrlHash({ urlHash: urlHash }) : null;

if (!feedback) {
  return new Response(null, { status: 404 });
}
---

<WebsiteLayout title="Feedback">
  <div class="flex justify-center items-center">
    <div class="mt-12 grid card w-11/12 xl:w-2/3 2xl:w-1/2 p-6 shadow-lg">
      <h2 class="text-3xl text-center">Feedback</h2>
      <form id="feedback" data-url-hash={urlHash}>
        <div class="space-y-4 mt-6 mb-4">
          <Input value={feedback.title} label="Event" dynamicWidth readonly />
          <Textarea
            id="content"
            value={feedback.content}
            label="Feedback"
            rows={10}
            dynamicWidth
            required
            readonly={feedback.content !== null}
          />
        </div>
        <button id="send" class="btn" disabled>Feedback senden</button>
      </form>
    </div>
  </div>
</WebsiteLayout>

<script>
  import { actions } from 'astro:actions';
  import { actionErrorPopup } from '@util/action';

  document.addEventListener('astro:page-load', () => {
    const form = document.getElementById('feedback') as HTMLFormElement;
    const content = document.getElementById('content') as HTMLTextAreaElement;
    const sendButton = document.getElementById('send') as HTMLButtonElement;

    form.addEventListener('submit', async (e) => {
      e.preventDefault();

      const { error } = await actions.feedback.submitFeedback({
        urlHash: form.dataset.urlHash!,
        content: content.value
      });

      if (error) {
        actionErrorPopup(error);
        return;
      }

      content.readOnly = true;
      sendButton.disabled = true;
    });
    content.addEventListener('input', () => (sendButton.disabled = content.value === '' || content.readOnly));
  });
</script>
