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 DepartmentsPage() {
  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);

  async function loadData() {
    setLoading(true);
    setError("");
    try {
      const data = await api.get(`/departments${showInactive ? "" : "?active=true"}`);
      setRows(Array.isArray(data) ? data : []);
    } catch (err) {
      setError(err.message || "Abteilungen 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]);

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

  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 saveDepartment(event) {
    event.preventDefault();
    setMessage("");
    setError("");

    const label = form.label.trim();
    const code = normalizeCode(form.code || label);

    if (!label) {
      setError("Bitte eine Bezeichnung eingeben.");
      return;
    }
    if (!code) {
      setError("Bitte einen gültigen Code eingeben.");
      return;
    }

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

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

  async function deleteDepartment(row) {
    const used = Number(row.usage_count || 0) > 0;
    const text = used
      ? `Abteilung „${row.label}“ wird in ${row.usage_count} Vorgang/Vorgängen verwendet und deshalb deaktiviert. Fortfahren?`
      : `Abteilung „${row.label}“ löschen?`;
    if (!window.confirm(text)) return;

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

  return (
    <>
      <style>{`
        .department-grid { display: grid; gap: 18px; }
        .department-badge { display: inline-block; padding: 4px 9px; border-radius: 999px; font-weight: 700; font-size: .84rem; }
        .department-badge.active { background: rgba(22, 163, 74, .12); color: #15803d; }
        .department-badge.inactive { background: rgba(100, 116, 139, .14); color: #475569; }
        .department-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);
        }
        .department-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);
        }
        .department-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);
        }
        .department-modal-header h2 { margin: 0; color: #0f172a; font-size: 1.35rem; }
        .department-modal-subtitle { margin: 6px 0 0; color: #64748b; line-height: 1.45; }
        .department-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);
        }
        .department-modal-close:hover { background: #f1f5f9; }
        .department-modal-body { padding: 22px 24px; overflow: auto; background: #ffffff; }
        .department-inline { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
        .department-modal-footer { display: flex; justify-content: flex-end; gap: 10px; flex-wrap: wrap; padding-top: 4px; }
        @media (max-width: 900px) {
          .department-inline { grid-template-columns: 1fr; }
          .department-modal-backdrop { padding: 12px; align-items: start; }
          .department-modal-panel { width: 100%; max-height: calc(100vh - 24px); }
        }
      `}</style>

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

        <SectionCard
          title="Abteilungen"
          subtitle="Hier werden die Abteilungen gepflegt, die im Vorgangs-Dialog unter Abteilung auswählbar 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}>Abteilung hinzufügen</button>
              <button className="btn secondary" type="button" onClick={loadData} disabled={loading}>{loading ? "Lade…" : "Aktualisieren"}</button>
            </div>
          }
        >
          <p className="muted">Aktive Abteilungen: {activeCount}. Abteilungen, die bereits in Vorgängen verwendet werden, werden beim Löschen deaktiviert, damit ältere Vorgänge lesbar bleiben.</p>
        </SectionCard>

        <SectionCard title="Vorhandene Abteilungen">
          <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} Vorgänge</td>
                    <td><span className={`department-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={() => deleteDepartment(row)}>{Number(row.usage_count || 0) > 0 ? "Deaktivieren" : "Löschen"}</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!rows.length ? <tr><td colSpan="6">Keine Abteilungen vorhanden.</td></tr> : null}
              </tbody>
            </table>
          </div>
        </SectionCard>
      </div>

      {modalOpen ? (
        <div className="department-modal-backdrop" onMouseDown={closeModal}>
          <div className="department-modal-panel" role="dialog" aria-modal="true" aria-labelledby="department-modal-title" onMouseDown={(event) => event.stopPropagation()}>
            <div className="department-modal-header">
              <div>
                <h2 id="department-modal-title">{editingId ? "Abteilung bearbeiten" : "Abteilung hinzufügen"}</h2>
                <p className="department-modal-subtitle">Der Code wird im Vorgang gespeichert. Beim Ändern des Codes werden vorhandene Vorgänge automatisch mit umgestellt.</p>
              </div>
              <button className="department-modal-close" type="button" onClick={closeModal} aria-label="Schließen">×</button>
            </div>

            <div className="department-modal-body">
              <form className="form-grid" onSubmit={saveDepartment}>
                <div className="department-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. personal" />
                  </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. Personal" />
                  </label>
                </div>

                <div className="department-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 Vorgang 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="department-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}
    </>
  );
}
