"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { updateTemplateAction, deleteTemplateAction } from "@/lib/actions/documents";
import { DOCUMENT_CATEGORY_LABELS, type DocumentCategory } from "@/lib/documentConstants";

export function TemplateRow({
  template,
  allowedCategories,
}: {
  template: {
    id: string;
    name: string;
    category: DocumentCategory;
    body: string;
    defaultIncludeLetterhead: boolean;
    defaultIncludeFooter: boolean;
    defaultFooterText: string;
    defaultIncludeRecipientAddress: boolean;
  };
  allowedCategories: readonly DocumentCategory[];
}) {
  const [pending, startTransition] = useTransition();
  const router = useRouter();

  function submit(form: HTMLFormElement) {
    const data = new FormData(form);
    startTransition(async () => {
      await updateTemplateAction(template.id, data);
      router.refresh();
    });
  }

  return (
    <details className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5">
      <summary className="flex items-center justify-between gap-3 cursor-pointer list-none">
        <span className="text-sm">
          {template.name}{" "}
          <span className="text-xs text-[var(--rk-ink-muted)]">· {DOCUMENT_CATEGORY_LABELS[template.category]}</span>
        </span>
        <div className="flex items-center gap-3 shrink-0">
          <span className="text-xs text-[var(--rk-ink-muted)]">Bearbeiten ▾</span>
          <button
            disabled={pending}
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              if (confirm(`Vorlage „${template.name}" wirklich löschen?`)) startTransition(() => deleteTemplateAction(template.id));
            }}
            className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50"
          >
            Löschen
          </button>
        </div>
      </summary>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          submit(e.currentTarget);
        }}
        className="mt-4 flex flex-col gap-3"
      >
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <input
            name="name"
            defaultValue={template.name}
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
          <select
            name="category"
            defaultValue={template.category}
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          >
            {allowedCategories.map((c) => (
              <option key={c} value={c}>
                {DOCUMENT_CATEGORY_LABELS[c]}
              </option>
            ))}
          </select>
        </div>
        <textarea
          name="body"
          defaultValue={template.body}
          rows={10}
          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"
        />

        <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)]">
            Vorbelegung beim Erstellen (danach pro Dokument änderbar)
          </p>
          <div className="flex flex-wrap gap-4">
            <label className="flex items-center gap-2 text-xs">
              <input type="checkbox" name="defaultIncludeLetterhead" 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="defaultIncludeFooter" 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="defaultIncludeRecipientAddress"
                defaultChecked={template.defaultIncludeRecipientAddress}
                className="h-3.5 w-3.5"
              />
              Empfängeradresse anzeigen (bei Briefen an eine Person)
            </label>
          </div>
          <textarea
            name="defaultFooterText"
            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"
          />
        </div>

        <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"
        >
          Speichern
        </button>
      </form>
    </details>
  );
}
