"use client";

import { useActionState, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { joinWaitlistAction } from "@/lib/actions/conventions";

// Kupfer-Button auf der Convention-Karte; beim Klick öffnet sich ein Modal
// mit den Anfrage-Feldern (Charakter/Idee, Wunsch-Tag, Wunsch-Uhrzeit,
// Sonstiges). Braucht ein eingeloggtes Konto (siehe joinWaitlistAction) —
// es entsteht KEIN Auftrag, nur ein Warteliste-Eintrag; Rakku bestätigt
// später im Admin mit festem Termin.
export function WaitlistForm({
  conventionId,
  locale,
  conventionStart,
  conventionEnd,
  triggerLabel,
}: {
  conventionId: string;
  locale: string;
  conventionStart: string; // ISO
  conventionEnd: string; // ISO
  triggerLabel: string;
}) {
  const t = useTranslations("conventionWaitlist");
  const [open, setOpen] = useState(false);
  const [state, formAction, pending] = useActionState(joinWaitlistAction, {});

  const days = useMemo(() => {
    const out: string[] = [];
    const end = new Date(conventionEnd);
    for (let d = new Date(conventionStart); d <= end; d.setDate(d.getDate() + 1)) {
      out.push(
        d.toLocaleDateString(locale === "en" ? "en-GB" : "de-DE", {
          weekday: "short",
          day: "numeric",
          month: "long",
        })
      );
    }
    return out;
  }, [conventionStart, conventionEnd, locale]);

  if (state.success) {
    return <p className="text-sm text-[var(--rk-accent)]">{t("submitSuccess")}</p>;
  }

  const fieldCls =
    "rounded-lg border border-white/15 bg-transparent px-3 py-2 text-sm text-[var(--rk-ink)] focus:border-white/50 focus:outline-none";
  const labelCls = "flex flex-col gap-1.5 text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]";
  // <option> erbt im nativen Popup (v. a. Linux/Chrome) die helle Feldschrift auf
  // hellem Grund -> unlesbar. Hintergrund + Farbe hier explizit hell-auf-dunkel setzen.
  const optionStyle = { backgroundColor: "#17171a", color: "#f5f5f4" };
  const req = <span className="text-[var(--rk-accent)]"> *</span>;

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="inline-block rounded-lg bg-[var(--rk-accent)] px-6 py-3 text-xs font-semibold uppercase tracking-[0.18em] text-[#141413] transition-opacity hover:opacity-90"
      >
        {triggerLabel}
      </button>

      {open && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          role="dialog"
          aria-modal="true"
          aria-label={t("formHeading")}
        >
          <div
            className="absolute inset-0 bg-black/75 backdrop-blur-sm"
            onClick={() => setOpen(false)}
          />
          <div className="relative w-full max-w-md rounded-2xl border border-white/10 bg-[var(--rk-surface)] p-6 shadow-[0_30px_80px_-20px_rgba(0,0,0,0.7)]">
            <div className="flex items-center justify-between">
              <h3 className="rk-wordmark text-lg">{t("formHeading")}</h3>
              <button
                type="button"
                onClick={() => setOpen(false)}
                aria-label={t("formCancel")}
                className="text-[var(--rk-ink-muted)] transition-colors hover:text-[var(--rk-ink)]"
              >
                ✕
              </button>
            </div>

            <form action={formAction} className="mt-5 flex flex-col gap-4">
              <input type="hidden" name="conventionId" value={conventionId} />
              <input type="hidden" name="locale" value={locale} />

              <label className={labelCls}>
                <span>
                  {t("characterLabel")}
                  {req}
                </span>
                <input name="character" required className={fieldCls} />
              </label>

              <div className="grid grid-cols-2 gap-3">
                <label className={labelCls}>
                  <span>
                    {t("dayLabel")}
                    {req}
                  </span>
                  <select
                    name="preferredDay"
                    required
                    defaultValue=""
                    className={`${fieldCls} [color-scheme:dark]`}
                  >
                    <option value="" disabled style={optionStyle}>
                      {t("selectPlaceholder")}
                    </option>
                    {days.map((d) => (
                      <option key={d} value={d} style={optionStyle}>
                        {d}
                      </option>
                    ))}
                  </select>
                </label>
                <label className={labelCls}>
                  <span>
                    {t("timeLabel")}
                    {req}
                  </span>
                  <select
                    name="preferredTime"
                    required
                    defaultValue=""
                    className={`${fieldCls} [color-scheme:dark]`}
                  >
                    <option value="" disabled style={optionStyle}>
                      {t("selectPlaceholder")}
                    </option>
                    <option value={t("timeMorning")} style={optionStyle}>
                      {t("timeMorning")}
                    </option>
                    <option value={t("timeAfternoon")} style={optionStyle}>
                      {t("timeAfternoon")}
                    </option>
                    <option value={t("timeEvening")} style={optionStyle}>
                      {t("timeEvening")}
                    </option>
                  </select>
                </label>
              </div>

              <label className={labelCls}>
                {t("noteLabel")}
                <textarea name="message" rows={2} className={`${fieldCls} resize-y`} />
              </label>

              <p className="text-[0.7rem] text-[var(--rk-ink-muted)]">{t("requiredNote")}</p>

              {state.error && <p className="text-xs text-red-400">{state.error}</p>}

              <div className="mt-1 flex gap-2">
                <button
                  type="submit"
                  disabled={pending}
                  className="rounded-lg bg-[var(--rk-accent)] px-5 py-2.5 text-xs font-semibold uppercase tracking-[0.16em] text-[#141413] transition-opacity hover:opacity-90 disabled:opacity-50"
                >
                  {pending ? "…" : t("formSubmit")}
                </button>
                <button
                  type="button"
                  onClick={() => setOpen(false)}
                  className="rounded-lg border border-white/25 px-5 py-2.5 text-xs uppercase tracking-[0.16em] text-[var(--rk-ink-muted)] transition-colors hover:border-white/50 hover:text-[var(--rk-ink)]"
                >
                  {t("formCancel")}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  );
}
