import { useEffect, useMemo, useState } from "react";
import SectionCard from "../components/SectionCard";
import { api } from "../lib/api";

function emptyForm() {
  return {
    code: "",
    label: "",
    description: "",
    sort_order: "1000",
    is_active: true,
  };
}

function normalizeCode(value) {
  return String(value || "")
    .trim()
    .toLowerCase()
    .replace(/ä/g, "ae")
    .replace(/ö/g, "oe")
    .replace(/ü/g, "ue")
    .replace(/ß/g, "ss")
    .replace(/[^a-z0-9]+/g, "_")
    .replace(/^_+|_+$/g, "")
    .slice(0, 80);
}

function toForm(row) {
  return {
    code: row.code || "",
    label: row.label || "",
    description: row.description || "",
    sort_order: String(row.sort_order ?? 1000),
    is_active: Boolean(row.is_active),
  };
}

export default function DocumentCategoriesPage() {
  const [rows, setRows] = useState([]);
  const [form, setForm] = useState(() => emptyForm());
  const [editingId, setEditingId] = useState("");
  const [modalOpen, setModalOpen] = useState(false);
  const [showInactive, setShowInactive] = useState(true);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const activeCount = useMemo(() => rows.filter((row) => row.is_active).length, [rows]);

  async function loadData() {
    setLoading(true);
    setError("");
    try {
      const data = await api.get(`/document-categories${showInactive ? "" : "?active=true"}`);
      setRows(Array.isArray(data) ? data : []);
    } catch (err) {
      setError(err.message || "Dokumentenkategorien konnten nicht geladen werden.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadData();
  }, [showInactive]);

  useEffect(() => {
    if (!modalOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    function handleKeyDown(event) {
      if (event.key === "Escape") closeModal();
    }

    window.addEventListener("keydown", handleKeyDown);
    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [modalOpen]);

  function updateField(field, value) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  function openCreateModal() {
    setEditingId("");
    setForm(emptyForm());
    setMessage("");
    setError("");
    setModalOpen(true);
  }

  function openEditModal(row) {
    setEditingId(String(row.id));
    setForm(toForm(row));
    setMessage("");
    setError("");
    setModalOpen(true);
  }

  function closeModal() {
    setModalOpen(false);
    setEditingId("");
    setForm(emptyForm());
  }

  async function saveCategory(event) {
    event.preventDefault();
    setMessage("");
    setError("");

    const payload = {
      ...form,
      code: normalizeCode(form.code || form.label),
      label: form.label.trim(),
      description: form.description.trim() || null,
      sort_order: Number(form.sort_order || 1000),
      is_active: Boolean(form.is_active),
    };

    if (!payload.code || !payload.label) {
      setError("Code und Bezeichnung sind erforderlich.");
      return;
    }

    try {
      if (editingId) {
        await api.put(`/document-categories/${editingId}`, payload);
        setMessage("Dokumentenkategorie gespeichert.");
      } else {
        await api.post("/document-categories", payload);
        setMessage("Dokumentenkategorie angelegt.");
      }
      closeModal();
      await loadData();
    } catch (err) {
      setError(err.message || "Dokumentenkategorie konnte nicht gespeichert werden.");
    }
  }

  async function deleteCategory(row) {
    const used = Number(row.usage_count || 0) > 0;
    const text = used
      ? `Dokumentenkategorie „${row.label}“ wird in ${row.usage_count} Dokument(en) verwendet und deshalb deaktiviert. Fortfahren?`
      : `Dokumentenkategorie „${row.label}“ löschen?`;
    if (!window.confirm(text)) return;

    setMessage("");
    setError("");
    try {
      await api.delete(`/document-categories/${row.id}`);
      setMessage(used ? "Dokumentenkategorie deaktiviert." : "Dokumentenkategorie gelöscht.");
      await loadData();
    } catch (err) {
      setError(err.message || "Dokumentenkategorie konnte nicht gelöscht werden.");
    }
  }

  return (
    <>
      <style>{`
        .document-category-grid { display: grid; gap: 18px; }
        .document-category-badge { display: inline-block; padding: 4px 9px; border-radius: 999px; font-weight: 700; font-size: .84rem; }
        .document-category-badge.active { background: rgba(22, 163, 74, .12); color: #15803d; }
        .document-category-badge.inactive { background: rgba(100, 116, 139, .14); color: #475569; }
        .document-category-modal-backdrop {
          position: fixed; inset: 0; z-index: 1000; display: grid; place-items: center; padding: 24px;
          background: rgba(15, 23, 42, 0.62); backdrop-filter: blur(2px);
        }
        .document-category-modal-panel {
          width: min(760px, 96vw); max-height: min(92vh, 920px); overflow: hidden; display: flex; flex-direction: column;
          border-radius: 22px; background: #ffffff; color: #0f172a; border: 1px solid rgba(15, 23, 42, 0.12);
          box-shadow: 0 30px 90px rgba(15, 23, 42, 0.34), 0 8px 24px rgba(15, 23, 42, 0.18);
        }
        .document-category-modal-header {
          display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding: 22px 24px 18px;
          background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%); border-bottom: 1px solid rgba(148, 164, 184, 0.28);
        }
        .document-category-modal-header h2 { margin: 0; color: #0f172a; font-size: 1.35rem; }
        .document-category-modal-subtitle { margin: 6px 0 0; color: #64748b; line-height: 1.45; }
        .document-category-modal-close {
          flex: 0 0 auto; width: 36px; height: 36px; border: 1px solid rgba(148, 164, 184, 0.35); border-radius: 999px;
          background: #ffffff; color: #0f172a; cursor: pointer; font-size: 1.3rem; line-height: 1; box-shadow: 0 4px 12px rgba(15, 23, 42, 0.08);
        }
        .document-category-modal-close:hover { background: #f1f5f9; }
        .document-category-modal-body { padding: 22px 24px; overflow: auto; background: #ffffff; }
        .document-category-inline { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
        .document-category-modal-footer { display: flex; justify-content: flex-end; gap: 10px; flex-wrap: wrap; padding-top: 4px; }
        @media (max-width: 900px) {
          .document-category-inline { grid-template-columns: 1fr; }
          .document-category-modal-backdrop { padding: 12px; align-items: start; }
          .document-category-modal-panel { width: 100%; max-height: calc(100vh - 24px); }
        }
      `}</style>

      <div className="document-category-grid">
        {error ? <div className="alert error">{error}</div> : null}
        {message ? <div className="alert success">{message}</div> : null}

        <SectionCard
          title="Dokumentenkategorien"
          subtitle="Hier werden die Kategorien gepflegt, die im Dokument-Dialog auswählbar und als Filter nutzbar sind."
          actions={
            <div className="row-actions">
              <label className="checkbox-row">
                <input type="checkbox" checked={showInactive} onChange={(event) => setShowInactive(event.target.checked)} />
                <span>Inaktive anzeigen</span>
              </label>
              <button className="btn" type="button" onClick={openCreateModal}>Kategorie hinzufügen</button>
              <button className="btn secondary" type="button" onClick={loadData} disabled={loading}>{loading ? "Lade…" : "Aktualisieren"}</button>
            </div>
          }
        >
          <p className="muted">Aktive Kategorien: {activeCount}. Kategorien, die bereits in Dokumenten verwendet werden, werden beim Löschen deaktiviert.</p>
        </SectionCard>

        <SectionCard title="Vorhandene Kategorien">
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr><th>Sort.</th><th>Code</th><th>Bezeichnung</th><th>Verwendung</th><th>Status</th><th>Aktionen</th></tr>
              </thead>
              <tbody>
                {rows.map((row) => (
                  <tr key={row.id}>
                    <td>{row.sort_order}</td>
                    <td><code>{row.code}</code></td>
                    <td><strong>{row.label}</strong>{row.description ? <><br /><small>{row.description}</small></> : null}</td>
                    <td>{row.usage_count || 0} Dokumente</td>
                    <td><span className={`document-category-badge ${row.is_active ? "active" : "inactive"}`}>{row.is_active ? "Aktiv" : "Inaktiv"}</span></td>
                    <td>
                      <div className="row-actions">
                        <button className="mini-btn" type="button" onClick={() => openEditModal(row)}>Bearbeiten</button>
                        <button className="mini-btn danger" type="button" onClick={() => deleteCategory(row)}>{Number(row.usage_count || 0) > 0 ? "Deaktivieren" : "Löschen"}</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!rows.length ? <tr><td colSpan="6">Keine Dokumentenkategorien vorhanden.</td></tr> : null}
              </tbody>
            </table>
          </div>
        </SectionCard>
      </div>

      {modalOpen ? (
        <div className="document-category-modal-backdrop" onMouseDown={closeModal}>
          <div className="document-category-modal-panel" role="dialog" aria-modal="true" aria-labelledby="document-category-modal-title" onMouseDown={(event) => event.stopPropagation()}>
            <div className="document-category-modal-header">
              <div>
                <h2 id="document-category-modal-title">{editingId ? "Dokumentenkategorie bearbeiten" : "Dokumentenkategorie hinzufügen"}</h2>
                <p className="document-category-modal-subtitle">Der Code dient als technischer Schlüssel, die Bezeichnung wird im Dokument-Dialog angezeigt.</p>
              </div>
              <button className="document-category-modal-close" type="button" onClick={closeModal} aria-label="Schließen">×</button>
            </div>

            <div className="document-category-modal-body">
              <form className="form-grid" onSubmit={saveCategory}>
                <div className="document-category-inline">
                  <label>
                    <span>Code</span>
                    <input className="input" required value={form.code} onChange={(event) => updateField("code", event.target.value)} onBlur={(event) => updateField("code", normalizeCode(event.target.value || form.label))} placeholder="z. B. protokoll" />
                  </label>
                  <label>
                    <span>Bezeichnung</span>
                    <input className="input" required value={form.label} onChange={(event) => updateField("label", event.target.value)} onBlur={() => { if (!form.code) updateField("code", normalizeCode(form.label)); }} placeholder="z. B. Protokoll" />
                  </label>
                </div>

                <div className="document-category-inline">
                  <label>
                    <span>Sortierung</span>
                    <input className="input" type="number" min="0" step="1" value={form.sort_order} onChange={(event) => updateField("sort_order", event.target.value)} />
                  </label>
                  <label className="checkbox-row" style={{ alignSelf: "end", minHeight: 42 }}>
                    <input type="checkbox" checked={form.is_active} onChange={(event) => updateField("is_active", event.target.checked)} />
                    <span>Aktiv und im Dokument auswählbar</span>
                  </label>
                </div>

                <label className="full">
                  <span>Beschreibung</span>
                  <textarea className="textarea" value={form.description} onChange={(event) => updateField("description", event.target.value)} />
                </label>

                <div className="document-category-modal-footer full">
                  <button className="btn secondary" type="button" onClick={closeModal}>Abbrechen</button>
                  <button className="btn" type="submit">{editingId ? "Speichern" : "Anlegen"}</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
