"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { updateContractTemplateAction } from "@/lib/actions/contractTemplates";

type Section = { heading: string; body: string; appendix?: boolean };

export function ContractTemplateEditor({
  type,
  title,
  sections: initialSections,
}: {
  type: "standard" | "tfp";
  title: string;
  sections: Section[];
}) {
  const [sections, setSections] = useState<Section[]>(initialSections);
  const [pending, startTransition] = useTransition();
  const [saved, setSaved] = useState(false);
  const router = useRouter();

  function updateSection(i: number, field: "heading" | "body", value: string) {
    setSections((prev) => prev.map((s, idx) => (idx === i ? { ...s, [field]: value } : s)));
  }

  function toggleAppendix(i: number, value: boolean) {
    setSections((prev) => prev.map((s, idx) => (idx === i ? { ...s, appendix: value } : s)));
  }

  function move(i: number, direction: "up" | "down") {
    const j = direction === "up" ? i - 1 : i + 1;
    if (j < 0 || j >= sections.length) return;
    setSections((prev) => {
      const next = [...prev];
      [next[i], next[j]] = [next[j], next[i]];
      return next;
    });
  }

  function remove(i: number) {
    setSections((prev) => prev.filter((_, idx) => idx !== i));
  }

  function addSection() {
    setSections((prev) => [...prev, { heading: "Neuer Abschnitt", body: "" }]);
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const formData = new FormData();
    for (const s of sections) {
      formData.append("heading", s.heading);
      formData.append("body", s.body);
      formData.append("appendix", s.appendix ? "on" : "off");
    }
    startTransition(async () => {
      await updateContractTemplateAction(type, formData);
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
      router.refresh();
    });
  }

  return (
    <form onSubmit={handleSubmit} className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-6 mb-8">
      <div className="flex items-center justify-between flex-wrap gap-2 mb-4">
        <h2 className="text-sm font-medium">{title}</h2>
        <div className="flex items-center gap-2">
          {saved && <span className="text-xs text-emerald-400">Gespeichert.</span>}
          <button
            type="submit"
            disabled={pending}
            className="text-xs border border-white/30 rounded-lg px-4 py-1.5 hover:border-white disabled:opacity-50"
          >
            {pending ? "…" : "Speichern"}
          </button>
        </div>
      </div>

      <div className="flex flex-col gap-3">
        {sections.map((s, i) => (
          <div key={i} className="border border-white/10 rounded-xl p-4">
            <div className="flex items-start gap-2 mb-2">
              <input
                value={s.heading}
                onChange={(e) => updateSection(i, "heading", e.target.value)}
                placeholder="Überschrift"
                className="flex-1 bg-transparent border border-white/15 rounded-lg px-3 py-1.5 text-sm font-medium focus:outline-none focus:border-white/50"
              />
              <div className="flex items-center gap-1 shrink-0">
                <button
                  type="button"
                  disabled={i === 0}
                  onClick={() => move(i, "up")}
                  className="text-xs text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] disabled:opacity-30 px-1"
                  title="Nach oben"
                >
                  ↑
                </button>
                <button
                  type="button"
                  disabled={i === sections.length - 1}
                  onClick={() => move(i, "down")}
                  className="text-xs text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] disabled:opacity-30 px-1"
                  title="Nach unten"
                >
                  ↓
                </button>
                <button
                  type="button"
                  onClick={() => {
                    if (confirm(`Abschnitt „${s.heading || "(ohne Titel)"}" wirklich entfernen?`)) remove(i);
                  }}
                  className="text-xs text-red-400/80 hover:text-red-400 px-1.5"
                  title="Entfernen"
                >
                  ✕
                </button>
              </div>
            </div>
            <textarea
              value={s.body}
              onChange={(e) => updateSection(i, "body", e.target.value)}
              rows={Math.min(16, Math.max(3, Math.ceil(s.body.length / 90)))}
              placeholder="Text (Leerzeile = neuer Absatz)"
              className="w-full bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm leading-relaxed focus:outline-none focus:border-white/50 resize-y font-mono"
            />
            <label className="flex items-center gap-2 text-xs text-[var(--rk-ink-muted)] mt-2">
              <input type="checkbox" checked={Boolean(s.appendix)} onChange={(e) => toggleAppendix(i, e.target.checked)} />
              Als Anhang nach der Unterschrift, auf eigener Seite (z. B. für AGB)
            </label>
          </div>
        ))}
        {sections.length === 0 && <p className="text-xs text-[var(--rk-ink-muted)]">Noch keine Abschnitte.</p>}
      </div>

      <button
        type="button"
        onClick={addSection}
        className="mt-3 text-xs border border-white/15 rounded-full px-3.5 py-1.5 hover:border-white/50 transition-colors"
      >
        + Abschnitt hinzufügen
      </button>
    </form>
  );
}
