<script lang="ts">
  import { submitRsvp, ApiError, type Guest, type GuestType } from "$lib/api";
  import { createWeddingInfo, formatFullDate } from "$lib/wedding-info.svelte";
  import { createRsvpStatus } from "$lib/rsvp-status.svelte";
  import Countdown from "$lib/components/Countdown.svelte";
  import PhotoBackground from "$lib/components/PhotoBackground.svelte";

  const wedding = createWeddingInfo();
  const rsvpStatus = createRsvpStatus();

  let now = $state(Date.now());
  $effect(() => {
    const id = setInterval(() => (now = Date.now()), 30_000);
    return () => clearInterval(id);
  });
  const isRsvpOpen = $derived(now < wedding.rsvpByDate.getTime());

  let guests = $state<Guest[]>([{ name: "", type: "adult" }]);
  let message = $state("");

  let status = $state<"idle" | "submitting" | "done" | "error">("idle");
  let errorMessage = $state("");

  function addGuest(type: GuestType) {
    guests.push({ name: "", type });
  }

  function removeGuest(index: number) {
    guests.splice(index, 1);
  }

  async function onSubmit(event: SubmitEvent) {
    event.preventDefault();
    const trimmedGuests = guests
      .map((g) => ({ name: g.name.trim(), type: g.type }))
      .filter((g) => g.name !== "");
    if (trimmedGuests.length === 0) {
      status = "error";
      errorMessage = "Please add at least one name.";
      return;
    }

    status = "submitting";
    errorMessage = "";
    try {
      await submitRsvp({
        guests: trimmedGuests,
        message: message || undefined,
      });
      status = "done";
      rsvpStatus.markSubmitted();
    } catch (err) {
      status = "error";
      errorMessage =
        err instanceof ApiError
          ? err.message
          : "Something went wrong. Please try again.";
    }
  }
</script>

<section
  class="relative flex flex-1 items-center justify-center overflow-hidden px-4 py-16 z-10"
>
  <PhotoBackground />

  <div
    class="border-surface-50/70 relative z-10 w-full max-w-md border px-6 py-12 sm:px-10 sm:py-14"
  >
    <div class="flex flex-col items-center gap-2 text-center">
      <p class="text-surface-200 text-base tracking-[0.25em] uppercase">
        Please join us to celebrate the union of
      </p>
      <h1 class="text-surface-50 font-malibu text-5xl">Zoé &amp; Shaldon</h1>
      <p class="text-surface-50 mt-3 text-2xl">
        {formatFullDate(wedding.date)}
      </p>
      <p class="text-surface-50 text-2xl">{wedding.ceremonyTime}</p>
      <p class="text-surface-50 mt-3 text-2xl">{wedding.venueName}</p>
      <p class="text-surface-50 text-2xl">{wedding.venueAddress}</p>
    </div>

    {#if isRsvpOpen}
      <div class="mt-8 flex flex-col items-center gap-3 text-center">
        <p class="text-surface-100 text-2xl">
          RSVP by {formatFullDate(wedding.rsvpByDate)}
        </p>
        <Countdown target={wedding.rsvpByDate} />
      </div>
    {/if}

    {#if !isRsvpOpen}
      <div class="border-error-400 rounded-base mt-8 border p-4 text-center">
        <p class="text-surface-50 text-lg font-medium">RSVP missed</p>
        <p class="text-surface-200 mt-1 text-base">
          The RSVP deadline has passed. Please contact us directly on {wedding.rsvpPhone}.
        </p>
      </div>
    {:else if status === "done"}
      <div class="preset-filled-primary-500 rounded-base mt-8 p-4 text-center">
        Thank you — your RSVP has been received!
      </div>
    {:else}
      <form class="mt-8 flex flex-col gap-4 w-full" onsubmit={onSubmit}>
        <div class="flex flex-col gap-2 w-full">
          <span class="label-text text-surface-100 text-2xl"
            >Who's coming? *</span
          >
          {#each guests as guest, i (i)}
            <div class="flex gap-2">
              <span
                class="preset-tonal-{guest.type === 'child'
                  ? 'secondary'
                  : 'primary'} rounded-base flex shrink-0 items-center px-2 text-2xl font-medium"
              >
                {guest.type === "child" ? "Child" : "Adult"}
              </span>
              <input
                class="input border-surface-300 dark:border-surface-700 focus:border-primary-500 border text-2xl"
                type="text"
                placeholder={guest.type === "child"
                  ? "Child's name"
                  : "Guest name"}
                required
                bind:value={guest.name}
                disabled={status === "submitting"}
              />
              {#if guests.length > 1}
                <button
                  type="button"
                  class="btn preset-filled-surface-200-800 text-2xl"
                  aria-label="Remove guest"
                  onclick={() => removeGuest(i)}
                  disabled={status === "submitting"}
                >
                  &minus;
                </button>
              {/if}
            </div>
          {/each}
          <div class="flex gap-2 w-full">
            <button
              type="button"
              class="btn preset-filled-surface-200-800 text-2xl self-start"
              onclick={() => addGuest("adult")}
              disabled={status === "submitting"}
            >
              + Add guest
            </button>
            <button
              type="button"
              class="btn preset-filled-surface-200-800 text-2xl self-start"
              onclick={() => addGuest("child")}
              disabled={status === "submitting"}
            >
              + Add child
            </button>
          </div>
        </div>

        <label class="label">
          <span class="label-text text-surface-100 text-2xl"
            >Message to the couple (optional)</span
          >
          <textarea
            class="textarea border-surface-300 dark:border-surface-700 focus:border-primary-500 border text-2xl"
            rows="3"
            bind:value={message}
            disabled={status === "submitting"}
          ></textarea>
        </label>

        {#if status === "error"}
          <p class="text-error-500 text-2xl">{errorMessage}</p>
        {/if}

        <button
          class="btn preset-filled-secondary-500 mt-2 text-2xl"
          type="submit"
          disabled={status === "submitting"}
        >
          {status === "submitting" ? "Sending…" : "Send RSVP"}
        </button>

        <p class="text-surface-200 text-center text-2xl">
          Or RSVP by phone: {wedding.rsvpPhone}
        </p>
      </form>
    {/if}
  </div>
</section>
