"use client";

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

const ACCENT_OPTIONS: { value: EventTheme["accent_color"]; label: string; swatch: string }[] = [
  { value: "primary", label: "Primary (#FF4E00)", swatch: "bg-kolabora-primary" },
  { value: "secondary", label: "Secondary (#FFFFAE)", swatch: "bg-kolabora-secondary" },
  { value: "tertiary", label: "Tertiary (#6CA0C0)", swatch: "bg-kolabora-tertiary" },
  { value: "neutral_dark", label: "Neutral Dark (#211A1D)", swatch: "bg-kolabora-neutral-dark" },
  { value: "neutral_white", label: "Neutral White (#FFFFFF)", swatch: "bg-kolabora-neutral-white border border-kolabora-neutral-dark/20" },
];

export function EventThemeForm({ eventId, initial }: { eventId: number; initial: EventTheme | null }) {
  const [accentColor, setAccentColor] = useState<EventTheme["accent_color"]>(
    initial?.accent_color ?? "primary",
  );
  const [heroLayout, setHeroLayout] = useState<EventTheme["hero_layout"]>(
    initial?.hero_layout ?? "standard",
  );
  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 res = await clientFetch(`/api/admin/events/${eventId}/theme`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ accent_color: accentColor, hero_layout: heroLayout }),
    });

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

    if (!res.ok) {
      const errorMessage = body?.errors?.event?.[0] ?? body?.message ?? "Failed to save visual theme.";
      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">
      <p className="text-xs text-kolabora-neutral-dark/70">
        Accent color and hero layout exclusive to Signature Event (FR-SIG-004) — the palette is
        restricted to the official Brand Visual Guideline colors (BAB IX), no free-form color codes.
      </p>

      <div>
        <p className="text-sm font-medium">Accent Color</p>
        <div className="mt-2 flex flex-col gap-2">
          {ACCENT_OPTIONS.map((option) => (
            <label key={option.value} className="flex items-center gap-2 text-sm">
              <input
                type="radio"
                name="accent_color"
                checked={accentColor === option.value}
                onChange={() => setAccentColor(option.value)}
              />
              <span className={`h-4 w-4 rounded-full ${option.swatch}`} />
              {option.label}
            </label>
          ))}
        </div>
      </div>

      <label className="flex flex-col gap-1 text-sm font-medium">
        Hero Layout
        <Select value={heroLayout} onChange={(e) => setHeroLayout(e.target.value as EventTheme["hero_layout"])}>
          <option value="standard">Standard (same as a regular event)</option>
          <option value="immersive">Immersive (full banner as hero)</option>
        </Select>
      </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>
  );
}
