"use client";
import { useEffect, useState } from "react";
import { aiPrompts, promptGroepLabels, type AiPrompt, type PromptGroep } from "@/data/ai-prompts";
import { leesModeldocumentHandoff, type ModeldocumentHandoff } from "@/lib/handoff";
import { downloadAanvullendBestand, type DownloadFormaat } from "@/lib/download-bestand";

const PROMPT_GROEP_VOLGORDE: PromptGroep[] = [
  "copilot-studio",
  "claude-agent",
  "copilot-m365",
  "prompt-compleet",
  "overige",
];

/** Standaard- en aanbevolen prompt: de Copilot Studio-agent met de Notary.AI-API-acties. */
const STANDAARD_PROMPT_ID = "notarieel-dossier-assistent-copilot-api";

export default function AiPromptsPage() {
  const [geselecteerdId, setGeselecteerdId] = useState<string>(
    aiPrompts.some((p) => p.id === STANDAARD_PROMPT_ID) ? STANDAARD_PROMPT_ID : aiPrompts[0]?.id ?? ""
  );
  const geselecteerd = aiPrompts.find((p) => p.id === geselecteerdId) ?? aiPrompts[0];
  const [handoff, setHandoff] = useState<ModeldocumentHandoff | null>(null);
  const [handoffGekopieerd, setHandoffGekopieerd] = useState(false);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- bestaand, bewust opslag-synchronisatiepatroon (IndexedDB/localStorage -> formulierstate); zie eslint.config.mjs
    setHandoff(leesModeldocumentHandoff());
  }, []);

  async function kopieerPromptMetDocument() {
    if (!handoff || !geselecteerd) return;
    await navigator.clipboard.writeText(
      `${geselecteerd.prompt}\n\n══════════ MODELDOCUMENT (MODUS A — IN TE VULLEN) ══════════\n\n${handoff.tekst}`
    );
    setHandoffGekopieerd(true);
    setTimeout(() => setHandoffGekopieerd(false), 2000);
  }

  return (
    <div className="max-w-5xl mx-auto p-4 md:p-8 space-y-6">
      <header>
        <h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
          🤖 AI-prompts
        </h1>
        <p className="text-sm text-slate-500 mt-1">
          Herbruikbare instructieprompts voor AI-agenten (Claude, Microsoft Copilot, …) bij
          dossierwerk. Kopieer de prompt en lever daarna het document en de dossierstukken aan.
          Het resultaat blijft een werkdocument dat de notaris naleest en valideert.
        </p>
      </header>

      {handoff && (
        <section className="bg-brand-50 border border-brand-200 rounded-xl shadow-sm p-5 space-y-3">
          <div className="flex items-start justify-between gap-3 flex-wrap">
            <div>
              <h2 className="text-sm font-semibold text-brand-900">
                📄 Modeldocument ontvangen: {handoff.titel}
              </h2>
              <p className="text-sm text-brand-800 mt-1">
                Gegenereerd in de module Modeldocumenten. Kies hieronder de gewenste promptversie
                en kopieer prompt + modeldocument samen — klaar om in de AI-agent te plakken,
                gevolgd door de dossierstukken (Modus A).
              </p>
            </div>
            <div className="flex gap-2 shrink-0">
              <button
                onClick={kopieerPromptMetDocument}
                className={`text-sm px-4 py-2 rounded-lg font-medium text-white ${
                  handoffGekopieerd ? "bg-emerald-600" : "bg-brand-600 hover:bg-brand-700"
                }`}
              >
                {handoffGekopieerd ? "✓ Gekopieerd" : "📋 Kopieer prompt + modeldocument"}
              </button>
              <button
                onClick={() => setHandoff(null)}
                className="text-sm px-3 py-2 rounded-lg border border-brand-300 text-brand-700 hover:bg-brand-100"
                aria-label="Sluit"
              >
                ✕
              </button>
            </div>
          </div>
          <details>
            <summary className="text-xs text-brand-700 cursor-pointer">Toon modeldocument</summary>
            <pre className="text-xs text-slate-700 whitespace-pre-wrap font-mono leading-relaxed p-4 bg-white rounded-lg mt-2 max-h-72 overflow-y-auto">
              {handoff.tekst}
            </pre>
          </details>
        </section>
      )}

      {aiPrompts.length > 1 && (
        <div className="space-y-3">
          {PROMPT_GROEP_VOLGORDE.map((groep) => {
            const prompts = aiPrompts.filter((p) => p.groep === groep);
            if (prompts.length === 0) return null;
            return (
              <div key={groep}>
                <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wide mb-1.5">
                  {promptGroepLabels[groep]}
                </h3>
                <div className="flex flex-wrap gap-2">
                  {prompts.map((p) => (
                    <button
                      key={p.id}
                      onClick={() => setGeselecteerdId(p.id)}
                      className={`text-sm px-3 py-1.5 rounded-lg border transition-colors ${
                        p.id === geselecteerdId
                          ? "bg-brand-600 text-white border-brand-600"
                          : "text-slate-600 border-slate-300 hover:border-brand-300"
                      }`}
                    >
                      {p.id === STANDAARD_PROMPT_ID ? "⭐ " : ""}
                      {p.titel}
                    </button>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {geselecteerd && <PromptDetail prompt={geselecteerd} />}
    </div>
  );
}

function PromptDetail({ prompt }: { prompt: AiPrompt }) {
  const [gekopieerd, setGekopieerd] = useState(false);
  const [toonVolledig, setToonVolledig] = useState(false);
  const [toonBestand, setToonBestand] = useState(false);
  const [bezigDownload, setBezigDownload] = useState<DownloadFormaat | null>(null);
  const [bezigDownloadPrompt, setBezigDownloadPrompt] = useState<DownloadFormaat | null>(null);
  const [bezigAlle, setBezigAlle] = useState(false);

  async function kopieer() {
    await navigator.clipboard.writeText(prompt.prompt);
    setGekopieerd(true);
    setTimeout(() => setGekopieerd(false), 2000);
  }

  function buildPromptInhoud(): string {
    return `# ${prompt.titel}\n\nVersie ${prompt.versie} — ${prompt.datum}\nAgent: ${prompt.agenten}\n\n${prompt.prompt}`;
  }

  async function downloadPrompt(formaat: DownloadFormaat) {
    if (bezigDownloadPrompt || bezigAlle) return;
    setBezigDownloadPrompt(formaat);
    try {
      await downloadAanvullendBestand(`${prompt.id}.md`, buildPromptInhoud(), formaat);
    } finally {
      setBezigDownloadPrompt(null);
    }
  }

  async function download(formaat: DownloadFormaat) {
    if (!prompt.aanvullendBestand || bezigDownload || bezigAlle) return;
    setBezigDownload(formaat);
    try {
      await downloadAanvullendBestand(
        prompt.aanvullendBestand.bestandsnaam,
        prompt.aanvullendBestand.inhoud,
        formaat
      );
    } finally {
      setBezigDownload(null);
    }
  }

  async function downloadAlle(formaat: DownloadFormaat) {
    if (!prompt.aanvullendBestand || bezigAlle) return;
    setBezigAlle(true);
    try {
      await downloadAanvullendBestand(`${prompt.id}.md`, buildPromptInhoud(), formaat);
      await downloadAanvullendBestand(
        prompt.aanvullendBestand.bestandsnaam,
        prompt.aanvullendBestand.inhoud,
        formaat
      );
    } finally {
      setBezigAlle(false);
    }
  }

  const isBezig = bezigDownload !== null || bezigDownloadPrompt !== null || bezigAlle;

  return (
    <div className="space-y-6">
      {/* Beschrijving */}
      <section className="bg-white border border-slate-200 rounded-xl shadow-sm p-5 space-y-3">
        <div className="flex items-start justify-between gap-3 flex-wrap">
          <div>
            <h2 className="text-lg font-semibold text-slate-900 flex items-center gap-2">
              {prompt.titel}
              {prompt.id === STANDAARD_PROMPT_ID && (
                <span className="text-xs font-medium px-2 py-0.5 rounded-full bg-brand-100 text-brand-700">
                  ⭐ Standaard (aanbevolen)
                </span>
              )}
            </h2>
            <p className="text-xs text-slate-400 mt-0.5">
              Versie {prompt.versie} · {prompt.datum} · {prompt.agenten}
            </p>
          </div>
          <button
            onClick={kopieer}
            className={`text-sm px-4 py-2 rounded-lg font-medium transition-colors shrink-0 ${
              gekopieerd
                ? "bg-emerald-600 text-white"
                : "bg-brand-600 text-white hover:bg-brand-700"
            }`}
          >
            {gekopieerd ? "✓ Gekopieerd" : "📋 Kopieer prompt"}
          </button>
        </div>
        <p className="text-sm text-slate-600">{prompt.doel}</p>
        {/* Download prompttekst */}
        <div className="pt-1 flex flex-wrap items-center gap-3">
          <div className="flex rounded-lg overflow-hidden border border-brand-500 text-sm font-medium">
            {(["md", "txt", "docx"] as DownloadFormaat[]).map((fmt, i) => (
              <button
                key={fmt}
                onClick={() => downloadPrompt(fmt)}
                disabled={isBezig}
                className={`px-3 py-1.5 bg-brand-500 text-white hover:bg-brand-600 disabled:opacity-60 transition-colors
                  ${i > 0 ? "border-l border-brand-400" : ""}`}
              >
                {bezigDownloadPrompt === fmt ? "…" : `⬇ .${fmt}`}
              </button>
            ))}
          </div>
          {prompt.aanvullendBestand && (
            <div className="flex rounded-lg overflow-hidden border border-slate-400 text-sm font-medium">
              {(["md", "txt", "docx"] as DownloadFormaat[]).map((fmt, i) => (
                <button
                  key={fmt}
                  onClick={() => downloadAlle(fmt)}
                  disabled={isBezig}
                  className={`px-3 py-1.5 bg-slate-600 text-white hover:bg-slate-700 disabled:opacity-60 transition-colors
                    ${i > 0 ? "border-l border-slate-500" : ""}`}
                >
                  {bezigAlle ? "…" : `⬇ Beide .${fmt}`}
                </button>
              ))}
            </div>
          )}
          <p className="text-xs text-slate-400">ℹ️ Microsoft Copilot werkt beter met .docx-bestanden.</p>
        </div>
      </section>

      {/* Prompttekst */}
      <section className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-100 flex items-center justify-between">
          <h3 className="text-sm font-semibold text-slate-700 uppercase tracking-wide">
            Prompttekst
          </h3>
          <button
            onClick={() => setToonVolledig((v) => !v)}
            className="text-xs text-brand-600 hover:text-brand-800"
          >
            {toonVolledig ? "Inklappen" : "Volledig tonen"}
          </button>
        </div>
        <pre
          className={`text-xs text-slate-700 whitespace-pre-wrap font-mono leading-relaxed p-5 bg-slate-50 overflow-y-auto ${
            toonVolledig ? "" : "max-h-96"
          }`}
        >
          {prompt.prompt}
        </pre>
      </section>

      {/* Aanvullend instructiebestand */}
      {prompt.aanvullendBestand && (
        <section className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
          <div className="px-5 py-3 border-b border-slate-100 flex items-center justify-between gap-3 flex-wrap">
            <div>
              <h3 className="text-sm font-semibold text-slate-700 uppercase tracking-wide">
                Aanvullend instructiebestand
              </h3>
              <p className="text-xs text-slate-400 mt-0.5 font-mono">
                {prompt.aanvullendBestand.bestandsnaam}
              </p>
              <p className="text-xs text-slate-400 mt-0.5">
                Versie {prompt.aanvullendBestand.versie} · Laatst gewijzigd: {prompt.aanvullendBestand.datum}
              </p>
            </div>
            <div className="flex items-center gap-3 shrink-0 flex-wrap">
              <button
                onClick={() => setToonBestand((v) => !v)}
                className="text-xs text-brand-600 hover:text-brand-800"
              >
                {toonBestand ? "Verberg inhoud" : "Toon inhoud"}
              </button>
              <div className="flex rounded-lg overflow-hidden border border-emerald-600 text-sm font-medium">
                {(["md", "txt", "docx"] as DownloadFormaat[]).map((fmt, i) => (
                  <button
                    key={fmt}
                    onClick={() => download(fmt)}
                    disabled={bezigDownload !== null}
                    className={`px-3 py-2 bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-60 transition-colors
                      ${i > 0 ? "border-l border-emerald-500" : ""}`}
                  >
                    {bezigDownload === fmt ? "…" : `⬇ .${fmt}`}
                  </button>
                ))}
              </div>
            </div>
          </div>
          <p className="text-sm text-slate-600 px-5 py-3">
            {prompt.aanvullendBestand.omschrijving}
          </p>
          {toonBestand && (
            <pre className="text-xs text-slate-700 whitespace-pre-wrap font-mono leading-relaxed p-5 bg-slate-50 border-t border-slate-100 max-h-96 overflow-y-auto">
              {prompt.aanvullendBestand.inhoud}
            </pre>
          )}
        </section>
      )}

      {/* Gebruikstips */}
      <section className="bg-white border border-slate-200 rounded-xl shadow-sm p-5">
        <h3 className="text-sm font-semibold text-slate-700 uppercase tracking-wide mb-3">
          Gebruikstips
        </h3>
        <ul className="space-y-2">
          {prompt.gebruikstips.map((tip, i) => (
            <li key={i} className="text-sm text-slate-600 flex gap-2">
              <span className="text-brand-400 shrink-0">•</span>
              {tip}
            </li>
          ))}
        </ul>
      </section>

      {/* Stappenplan verdere verbetering */}
      <section className="bg-white border border-slate-200 rounded-xl shadow-sm p-5">
        <h3 className="text-sm font-semibold text-slate-700 uppercase tracking-wide mb-1">
          Stappenplan — het resultaat verder verbeteren
        </h3>
        <p className="text-xs text-slate-400 mb-3">
          Volgorde voor het kantoor om deze prompt en de output ervan stap voor stap te verfijnen.
        </p>
        <ol className="space-y-3">
          {prompt.stappenplan.map((s) => (
            <li key={s.stap} className="text-sm">
              <p className="font-medium text-slate-800">{s.stap}</p>
              <p className="text-slate-600">{s.omschrijving}</p>
            </li>
          ))}
        </ol>
      </section>
    </div>
  );
}
