"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;
};

// Aus dem Mitarbeiterprofil automatisch befüllt, sobald oben ein Mitarbeiter
// ausgewählt ist.
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",
};

// 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];
    }
  }
  const initialBody = fillTemplate(template.body, autoValues);

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

  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 — danach frei bearbeitbar. */}
      <div key={`${templateId}-${clientId}`} className="flex flex-col gap-3">
        <input type="hidden" name="templateId" value={templateId} />
        <input type="hidden" name="clientId" value={clientId} />

        <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-2 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>
                <p className="leading-relaxed">
                  <span className="text-amber-400">✎ bitte unten im Text von Hand ergänzen:</span>{" "}
                  {manualTokens.map((tok) => `{{${tok}}}`).join(", ")}
                </p>
                <ul className="mt-1.5 flex flex-col gap-2 text-[var(--rk-ink-muted)]">
                  {manualTokens.map((tok) => (
                    <li key={tok} className="whitespace-pre-line">
                      <code>{`{{${tok}}}`}</code> — {TOKEN_DESCRIPTIONS[tok] || "(keine Beschreibung hinterlegt)"}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        )}

        <label className="flex flex-col gap-1 text-xs">
          <span className="text-[var(--rk-ink-muted)]">
            Dokumenttext {client && "— aus Vorlage vorbefüllt, frei bearbeitbar"}
          </span>
          <textarea
            name="body"
            defaultValue={initialBody}
            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>

      <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>
  );
}
