"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { HomepageSection } from "@/types/cms";
import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
import { useToast } from "@/components/ui/toast";
import { FOCUS_RING_TIGHT_CLASSES, cardClasses } from "@/components/ui/styles";
import { clientFetch } from "@/lib/api/client";
import { cn } from "@/lib/utils";

interface HeroFormState {
  hero_title: string;
  hero_subtitle: string;
  hero_cta_label: string;
  hero_cta_url: string;
}

function toHeroForm(section: HomepageSection): HeroFormState {
  return {
    hero_title: section.hero_title ?? "",
    hero_subtitle: section.hero_subtitle ?? "",
    hero_cta_label: section.hero_cta_label ?? "",
    hero_cta_url: section.hero_cta_url ?? "",
  };
}

/** FR-CMS-007/014: toggle visibility, reorder (up/down), and edit Hero copy override. */
export function HomepageSectionManager({ sections }: { sections: HomepageSection[] }) {
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [editingHero, setEditingHero] = useState(false);
  const [heroForm, setHeroForm] = useState<HeroFormState>(() => {
    const hero = sections.find((s) => s.key === "hero");
    return hero ? toHeroForm(hero) : { hero_title: "", hero_subtitle: "", hero_cta_label: "", hero_cta_url: "" };
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [togglingId, setTogglingId] = useState<number | null>(null);
  const [isMoving, setIsMoving] = useState(false);
  const { toast } = useToast();

  async function toggleVisible(section: HomepageSection) {
    setError(null);
    setTogglingId(section.id);
    const res = await clientFetch(`/api/admin/cms/homepage-sections/${section.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ is_visible: !section.is_visible }),
    });
    setTogglingId(null);
    const body = await res.json().catch(() => null);
    if (!res.ok) {
      const message = body?.message ?? "Failed to change section visibility.";
      setError(message);
      toast(message, "error");
      return;
    }
    router.refresh();
  }

  async function move(index: number, direction: -1 | 1) {
    const targetIndex = index + direction;
    if (targetIndex < 0 || targetIndex >= sections.length) return;

    const reordered = [...sections];
    [reordered[index], reordered[targetIndex]] = [reordered[targetIndex], reordered[index]];

    setError(null);
    setIsMoving(true);
    const res = await clientFetch("/api/admin/cms/homepage-sections/reorder", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ids: reordered.map((s) => s.id) }),
    });
    setIsMoving(false);
    const body = await res.json().catch(() => null);
    if (!res.ok) {
      const message = body?.message ?? "Failed to change section order.";
      setError(message);
      toast(message, "error");
      return;
    }
    router.refresh();
  }

  async function handleHeroSubmit(sectionId: number, isVisible: boolean) {
    setError(null);
    setIsSubmitting(true);
    const res = await clientFetch(`/api/admin/cms/homepage-sections/${sectionId}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        is_visible: isVisible,
        hero_title: heroForm.hero_title || null,
        hero_subtitle: heroForm.hero_subtitle || null,
        hero_cta_label: heroForm.hero_cta_label || null,
        hero_cta_url: heroForm.hero_cta_url || null,
      }),
    });
    setIsSubmitting(false);
    const body = await res.json().catch(() => null);
    if (!res.ok) {
      const message = body?.message ?? "Failed to save Hero content.";
      setError(message);
      toast(message, "error");
      return;
    }
    setEditingHero(false);
    toast("Hero content saved successfully.", "success");
    router.refresh();
  }

  return (
    <div>
      <p className="text-sm text-kolabora-neutral-dark/70">
        Control which sections show on the Homepage and their order (FR-CMS-007/014).
      </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((section, index) => (
          <div key={section.id}>
            <div className="flex items-center justify-between gap-3 px-4 py-3">
              <div className="flex items-center gap-3">
                <div className="flex flex-col gap-0.5">
                  <button
                    type="button"
                    onClick={() => move(index, -1)}
                    disabled={index === 0 || isMoving}
                    aria-label="Move up"
                    className={cn(
                      "rounded text-xs text-kolabora-neutral-dark/70 hover:text-kolabora-primary disabled:opacity-30",
                      FOCUS_RING_TIGHT_CLASSES,
                    )}
                  >
                    &uarr;
                  </button>
                  <button
                    type="button"
                    onClick={() => move(index, 1)}
                    disabled={index === sections.length - 1 || isMoving}
                    aria-label="Move down"
                    className={cn(
                      "rounded text-xs text-kolabora-neutral-dark/70 hover:text-kolabora-primary disabled:opacity-30",
                      FOCUS_RING_TIGHT_CLASSES,
                    )}
                  >
                    &darr;
                  </button>
                </div>
                <div>
                  <p className="font-medium">{section.label}</p>
                  <p className="font-mono text-xs text-kolabora-neutral-dark/70">{section.key}</p>
                </div>
              </div>
              <div className="flex shrink-0 items-center gap-2">
                {section.key === "hero" && (
                  <Button
                    type="button"
                    variant="secondary"
                    size="sm"
                    onClick={() => {
                      setHeroForm(toHeroForm(section));
                      setEditingHero((v) => !v);
                    }}
                  >
                    {editingHero ? "Close" : "Edit Content"}
                  </Button>
                )}
                <label className="flex items-center gap-1.5 text-sm">
                  <input
                    type="checkbox"
                    checked={section.is_visible}
                    disabled={togglingId === section.id}
                    onChange={() => toggleVisible(section)}
                  />
                  Visible
                </label>
              </div>
            </div>

            {section.key === "hero" && editingHero && (
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  handleHeroSubmit(section.id, section.is_visible);
                }}
                className="flex flex-col gap-2 border-t border-kolabora-neutral-dark/10 px-4 py-3"
              >
                <p className="text-xs text-kolabora-neutral-dark/70">
                  Only applies when no Signature Event is active (FR-SIG-003 always takes over the Hero with
                  real event data). Leave empty to use the default text.
                </p>
                <Input
                  size="sm"
                  value={heroForm.hero_title}
                  onChange={(e) => setHeroForm({ ...heroForm, hero_title: e.target.value })}
                  placeholder="Hero Title (optional, default: 'Discover & Host the Best Events')"
                />
                <Textarea
                  size="sm"
                  value={heroForm.hero_subtitle}
                  onChange={(e) => setHeroForm({ ...heroForm, hero_subtitle: e.target.value })}
                  placeholder="Hero Subtitle (optional)"
                  rows={2}
                />
                <div className="flex gap-2">
                  <Input
                    size="sm"
                    value={heroForm.hero_cta_label}
                    onChange={(e) => setHeroForm({ ...heroForm, hero_cta_label: e.target.value })}
                    placeholder="CTA Button Label (optional, default: 'Explore Events')"
                    className="flex-1"
                  />
                  <Input
                    size="sm"
                    value={heroForm.hero_cta_url}
                    onChange={(e) => setHeroForm({ ...heroForm, hero_cta_url: e.target.value })}
                    placeholder="CTA Button URL (optional, default: /events)"
                    className="flex-1"
                  />
                </div>
                <Button type="submit" loading={isSubmitting} className="ml-auto">
                  Save
                </Button>
              </form>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
