"use client";

import { useActionState, useState } from "react";
import { generateDocumentAction } from "@/lib/actions/documents";
import { fillTemplate, extractTokens, DOCUMENT_CATEGORY_LABELS, type DocumentCategory } from "@/lib/documentConstants";
import { TOKEN_DESCRIPTIONS } from "@/lib/documentTokenGlossary";
import { formatDateDE } from "@/lib/orderConstants";

type TemplateOption = {
  id: string;
  name: string;
  category: DocumentCategory;
  body: string;
  defaultIncludeLetterhead: boolean;
  defaultIncludeFooter: boolean;
  defaultFooterText: string;
  defaultIncludeRecipientAddress: boolean;
};
type ClientOption = {
  id: string;
  name: string;
  email: string;
  departmentName: string;
  positionName: string;
  address: string;
  employmentStartDate: string;
  birthDate: string;
  probezeit: string;
  stundenlohn: string;
  gehalt: string;
  urlaubstage: string;
};

// Aus dem Mitarbeiterprofil automatisch befüllt, sobald oben ein Mitarbeiter
// ausgewählt ist. urlaubstage ergänzt am 25.09.2026, sobald das
// Urlaubs-Kontingent (Client.vacationDaysPerYear) als Standardwert existiert
// - vorher gab es dafür keine Datenquelle, siehe Personalsystem-Notiz.
const AUTO_FIELDS: Record<string, keyof ClientOption> = {
  name: "name",
  email: "email",
  department: "departmentName",
  position: "positionName",
  address: "address",
  startDate: "employmentStartDate",
  geburtsdatum: "birthDate",
  probezeit: "probezeit",
  stundenlohn: "stundenlohn",
  gehalt: "gehalt",
  urlaubstage: "urlaubstage",
};

// Unabhängig vom ausgewählten Mitarbeiter immer befüllt (Kontext des
// Erstellungszeitpunkts, nicht des Profils).
function contextValues(): Record<string, string> {
  return { ausstellungsdatum: formatDateDE(new Date()) };
}

export function GenerateDocumentPanel({
  templates,
  clients,
  allowedCategories,
}: {
  templates: TemplateOption[];
  clients: ClientOption[];
  allowedCategories: readonly DocumentCategory[];
}) {
  const [templateId, setTemplateId] = useState("");
  const [clientId, setClientId] = useState("");
  const [state, formAction, pending] = useActionState(generateDocumentAction, {});

  const blankTemplate: TemplateOption = {
    id: "",
    name: "",
    category: allowedCategories[0],
    body: "",
    defaultIncludeLetterhead: true,
    defaultIncludeFooter: true,
    defaultFooterText: "",
    defaultIncludeRecipientAddress: false,
  };
  const template = templates.find((t) => t.id === templateId) ?? blankTemplate;
  const client = clients.find((c) => c.id === clientId);

  const autoValues: Record<string, string> = { ...contextValues() };
  if (client) {
    for (const [token, field] of Object.entries(AUTO_FIELDS)) {
      if (client[field]) autoValues[token] = client[field];
    }
  }

  return (
    <form action={formAction} className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5 flex flex-col gap-4">
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <label className="flex flex-col gap-1 text-xs">
          <span className="text-[var(--rk-ink-muted)]">Vorlage</span>
          <select
            value={templateId}
            onChange={(e) => setTemplateId(e.target.value)}
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-sm"
          >
            <option value="">— Leeres Dokument —</option>
            {templates.map((t) => (
              <option key={t.id} value={t.id}>
                {t.name} ({DOCUMENT_CATEGORY_LABELS[t.category]})
              </option>
            ))}
          </select>
        </label>
        <label className="flex flex-col gap-1 text-xs">
          <span className="text-[var(--rk-ink-muted)]">Für Mitarbeiter (optional)</span>
          <select
            value={clientId}
            onChange={(e) => setClientId(e.target.value)}
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-sm"
          >
            <option value="">— Keiner / allgemein —</option>
            {clients.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>
        </label>
      </div>

      {/* Remounten + neu vorbelegen, sobald Vorlage oder Mitarbeiter wechselt. */}
      <DocumentFieldsForm
        key={`${templateId}-${clientId}`}
        template={template}
        client={client}
        autoValues={autoValues}
        allowedCategories={allowedCategories}
      />

      <div className="flex items-center gap-3">
        <button
          type="submit"
          disabled={pending}
          className="self-start border border-white/30 rounded-lg px-4 py-2 text-xs uppercase tracking-[0.15em] hover:border-white disabled:opacity-50"
        >
          Dokument erstellen
        </button>
        {state.error && <span className="text-sm text-red-400">{state.error}</span>}
        {state.documentId && (
          <a
            href={`/api/documents/${state.documentId}/pdf`}
            target="_blank"
            rel="noopener noreferrer"
            className="text-sm text-emerald-400 underline"
          >
            PDF öffnen
          </a>
        )}
      </div>
    </form>
  );
}

// Eigene, per key remountende Komponente (statt State im Eltern-Scope), weil
// die "was fehlt noch"-Felder unten (manualValues) UND die Live-Vorschau bei
// jedem Vorlagen-/Mitarbeiterwechsel wieder bei null anfangen müssen - ein
// React-Remount über den key erledigt das automatisch, ganz ohne manuelles
// Reset-Effect.
// Statt Platzhalter nur als Text-Hinweis zum manuellen Ersetzen in der langen
// Textarea zu zeigen (alter Zustand), bekommt jeder noch offene Platzhalter
// jetzt ein eigenes Eingabefeld ("Popup/Formular, das alles abfragt, was
// nicht automatisch übernommen werden kann" - Nutzer-Wunsch, analog zum
// TFP-Vertragsformular). Die Vorschau folgt diesen Feldern live, bis jemand
// direkt in die Textarea tippt - ab dann bleibt die eigene Bearbeitung
// führend, damit ein späteres Ausfüllen eines Formularfelds nichts überschreibt.
function DocumentFieldsForm({
  template,
  client,
  autoValues,
  allowedCategories,
}: {
  template: TemplateOption;
  client: ClientOption | undefined;
  autoValues: Record<string, string>;
  allowedCategories: readonly DocumentCategory[];
}) {
  const [manualValues, setManualValues] = useState<Record<string, string>>({});
  const [textEdited, setTextEdited] = useState(false);
  const [manualBody, setManualBody] = useState("");

  const tokensInTemplate = extractTokens(template.body);
  const autoTokens = tokensInTemplate.filter((tok) => autoValues[tok]);
  const manualTokens = tokensInTemplate.filter((tok) => !autoValues[tok]);

  const computedBody = fillTemplate(template.body, { ...autoValues, ...manualValues });
  const displayedBody = textEdited ? manualBody : computedBody;

  return (
    <div className="flex flex-col gap-3">
      <input type="hidden" name="templateId" value={template.id} />
      <input type="hidden" name="clientId" value={client?.id ?? ""} />

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <label className="flex flex-col gap-1 text-xs">
          <span className="text-[var(--rk-ink-muted)]">Dokumenttitel</span>
          <input
            name="templateName"
            defaultValue={template.name}
            required
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
        </label>
        <label className="flex flex-col gap-1 text-xs">
          <span className="text-[var(--rk-ink-muted)]">Kategorie</span>
          <select
            name="category"
            defaultValue={template.category}
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-sm"
          >
            {allowedCategories.map((c) => (
              <option key={c} value={c}>
                {DOCUMENT_CATEGORY_LABELS[c]}
              </option>
            ))}
          </select>
        </label>
      </div>

      {tokensInTemplate.length > 0 && (
        <div className="rounded-lg border border-white/10 bg-[var(--rk-bg)] p-3 flex flex-col gap-3 text-xs">
          <p className="uppercase tracking-[0.08em] text-[var(--rk-ink-muted)]">Platzhalter in dieser Vorlage</p>
          {autoTokens.length > 0 && (
            <p className="leading-relaxed">
              <span className="text-emerald-400">✓ automatisch ausgefüllt:</span>{" "}
              {autoTokens.map((tok) => `{{${tok}}}`).join(", ")}
            </p>
          )}
          {manualTokens.length > 0 && (
            <div className="flex flex-col gap-2">
              <p className="leading-relaxed text-amber-400">✎ bitte ausfüllen:</p>
              {manualTokens.map((tok) => (
                <label key={tok} className="flex flex-col gap-1">
                  <span className="text-[var(--rk-ink-muted)]">
                    <code>{`{{${tok}}}`}</code> — {TOKEN_DESCRIPTIONS[tok] || "(keine Beschreibung hinterlegt)"}
                  </span>
                  <input
                    value={manualValues[tok] ?? ""}
                    onChange={(e) => setManualValues((prev) => ({ ...prev, [tok]: e.target.value }))}
                    className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
                  />
                </label>
              ))}
            </div>
          )}
        </div>
      )}

      <label className="flex flex-col gap-1 text-xs">
        <span className="text-[var(--rk-ink-muted)]">
          Dokumenttext {client && "— aus Vorlage + Feldern oben vorbefüllt, frei bearbeitbar"}
        </span>
        <textarea
          name="body"
          value={displayedBody}
          onChange={(e) => {
            setTextEdited(true);
            setManualBody(e.target.value);
          }}
          required
          rows={14}
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-white/50 resize-y font-mono"
        />
      </label>

      <div className="flex flex-col gap-2 border-t border-white/10 pt-3">
        <p className="text-xs uppercase tracking-[0.08em] text-[var(--rk-ink-muted)]">Briefkopf & Footer</p>
        <div className="flex flex-wrap gap-4">
          <label className="flex items-center gap-2 text-xs">
            <input type="checkbox" name="includeLetterhead" defaultChecked={template.defaultIncludeLetterhead} className="h-3.5 w-3.5" />
            Briefkopf anzeigen
          </label>
          <label className="flex items-center gap-2 text-xs">
            <input type="checkbox" name="includeFooter" defaultChecked={template.defaultIncludeFooter} className="h-3.5 w-3.5" />
            Footer anzeigen
          </label>
          <label className="flex items-center gap-2 text-xs">
            <input
              type="checkbox"
              name="includeRecipientAddress"
              defaultChecked={template.defaultIncludeRecipientAddress}
              className="h-3.5 w-3.5"
            />
            Empfängeradresse anzeigen
          </label>
        </div>
        <textarea
          name="footerText"
          defaultValue={template.defaultFooterText}
          rows={2}
          placeholder="Footer-Text (leer = automatisch „Erstellt am … · Geschäftsname“)"
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-xs focus:outline-none focus:border-white/50 resize-y"
        />
        <textarea
          name="recipientAddress"
          defaultValue={client?.address || ""}
          rows={3}
          placeholder="Empfängeradresse (Name + Anschrift, eine Zeile pro Zeile) — bei ausgewähltem Mitarbeiter automatisch aus dem Profil übernommen"
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-xs focus:outline-none focus:border-white/50 resize-y"
        />
      </div>
    </div>
  );
}
