"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { SignatureProfile } from "@/types/event";
import { clientFetch } from "@/lib/api/client";
import { cardClasses } from "@/components/ui/styles";
import { cn } from "@/lib/utils";

type ToggleKey =
  | "show_about"
  | "show_venue_date"
  | "show_event_card"
  | "show_lineup"
  | "show_project"
  | "show_brand"
  | "show_documentation";

// Fixed set, in the same order they render on the public page (see
// SignatureEventPage.tsx) — Hero is deliberately not included here, it's
// structurally pinned to About's slide-up reveal, not a standalone section.
const SECTIONS: Array<{ key: ToggleKey; label: string }> = [
  { key: "show_about", label: "About" },
  { key: "show_venue_date", label: "Venue Map & Date" },
  { key: "show_event_card", label: "Event Card" },
  { key: "show_lineup", label: "Artist Lineup" },
  { key: "show_project", label: "Project" },
  { key: "show_brand", label: "Brand Partner" },
  { key: "show_documentation", label: "Documentation" },
];

/** Per-section show/hide toggles for the public Signature page — each checkbox saves immediately, same pattern as HomepageSectionManager's toggleVisible. */
export function SignatureSectionVisibilityForm({
  eventId,
  initial,
}: {
  eventId: number;
  initial: SignatureProfile | null;
}) {
  const router = useRouter();
  const [values, setValues] = useState<Record<ToggleKey, boolean>>(() => {
    const entries = SECTIONS.map(({ key }) => [key, initial?.[key] ?? true] as const);
    return Object.fromEntries(entries) as Record<ToggleKey, boolean>;
  });
  const [pendingKey, setPendingKey] = useState<ToggleKey | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function toggle(key: ToggleKey) {
    const next = !values[key];
    setError(null);
    setPendingKey(key);
    setValues((v) => ({ ...v, [key]: next }));

    const res = await clientFetch(`/api/admin/events/${eventId}/signature-profile`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ [key]: next }),
    });

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

    if (!res.ok) {
      setValues((v) => ({ ...v, [key]: !next }));
      setError(body?.message ?? "Failed to change section visibility.");
      return;
    }

    router.refresh();
  }

  return (
    <div>
      <p className="text-sm text-kolabora-neutral-dark/70">
        Hide sections that aren&apos;t ready to show on the public Signature Event page. Hero is always
        shown (tied directly to About&apos;s transition animation).
      </p>
      {error && <p className="mt-2 text-sm text-red-600">{error}</p>}

      <div className={cn("mt-3 flex flex-col divide-y divide-kolabora-neutral-dark/10", cardClasses())}>
        {SECTIONS.map(({ key, label }) => (
          <label key={key} className="flex items-center justify-between gap-3 px-4 py-3 text-sm">
            <span className="font-medium">{label}</span>
            <input
              type="checkbox"
              checked={values[key]}
              disabled={pendingKey === key}
              onChange={() => toggle(key)}
            />
          </label>
        ))}
      </div>
    </div>
  );
}
