"use client";

import { useState, type FormEvent } from "react";
import type { SignatureProfile } from "@/types/event";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/input";
import { useToast } from "@/components/ui/toast";
import { clientFetch } from "@/lib/api/client";

/**
 * Free-text marketing blurbs (Promo & Voucher, Promo Spesial) and Rules list
 * for the public detail page — not connected to the real Promo/Voucher
 * module, purely admin-authored copy (per explicit user decision 2026-07-23).
 * `rules` is edited as one point per line and split/joined on submit/load.
 */
export function SignatureContentForm({ eventId, initial }: { eventId: number; initial: SignatureProfile | null }) {
  const [aboutText, setAboutText] = useState(initial?.about_text ?? "");
  const [promoText, setPromoText] = useState(initial?.promo_text ?? "");
  const [promoSpecialText, setPromoSpecialText] = useState(initial?.promo_special_text ?? "");
  const [rulesText, setRulesText] = useState((initial?.rules ?? []).join("\n"));
  const [showLogo, setShowLogo] = useState(initial?.main_event_show_logo ?? true);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();

  async function handleSubmit(formEvent: FormEvent<HTMLFormElement>) {
    formEvent.preventDefault();
    setMessage(null);
    setError(null);
    setIsSubmitting(true);

    const rules = rulesText
      .split("\n")
      .map((line) => line.trim())
      .filter((line) => line.length > 0);

    const res = await clientFetch(`/api/admin/events/${eventId}/signature-profile`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        about_text: aboutText || null,
        promo_text: promoText || null,
        promo_special_text: promoSpecialText || null,
        rules,
        main_event_show_logo: showLogo,
      }),
    });

    setIsSubmitting(false);
    const body = await res.json().catch(() => null);

    if (!res.ok) {
      const errorMessage = body?.errors?.event?.[0] ?? body?.message ?? "Failed to save content.";
      setError(errorMessage);
      toast(errorMessage, "error");
      return;
    }

    const successMessage = body?.message ?? "Saved.";
    setMessage(successMessage);
    toast(successMessage, "success");
  }

  return (
    <form onSubmit={handleSubmit} className="mt-4 flex max-w-md flex-col gap-4">
      <label className="flex flex-col gap-1 text-sm font-medium">
        About Event (Detail page only)
        <Textarea
          rows={4}
          placeholder="Event description coming soon."
          value={aboutText}
          onChange={(e) => setAboutText(e.target.value)}
        />
      </label>
      <label className="flex flex-col gap-1 text-sm font-medium">
        Promo &amp; Voucher
        <Textarea
          rows={3}
          placeholder="Stay tuned for the latest promo and voucher codes for this event."
          value={promoText}
          onChange={(e) => setPromoText(e.target.value)}
        />
      </label>
      <label className="flex flex-col gap-1 text-sm font-medium">
        Special Promo
        <Textarea
          rows={3}
          placeholder="A special promo is coming — stay tuned."
          value={promoSpecialText}
          onChange={(e) => setPromoSpecialText(e.target.value)}
        />
      </label>
      <label className="flex flex-col gap-1 text-sm font-medium">
        Rules (one point per line)
        <Textarea
          rows={5}
          placeholder={"Outside food is not allowed\nTickets are non-transferable"}
          value={rulesText}
          onChange={(e) => setRulesText(e.target.value)}
        />
      </label>

      <label className="flex items-center gap-2 text-sm font-medium">
        <input type="checkbox" checked={showLogo} onChange={(e) => setShowLogo(e.target.checked)} />
        Show the Signaturee logo &amp; tagline centered on the Main Event thumbnail
      </label>

      {message && <p className="text-sm text-green-600">{message}</p>}
      {error && <p className="text-sm text-red-600">{error}</p>}
      <Button type="submit" loading={isSubmitting} className="mt-1 self-start">
        Save
      </Button>
    </form>
  );
}
