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

function agendaStatusLabel(value) {
  const labels = {
    offen: "Offen",
    in_sitzung: "In Sitzung",
    rueckfrage: "Rückfrage",
    klaerung: "Klärung",
    erledigt: "Erledigt",
  };
  return labels[value] || value || "Offen";
}

function returnTypeLabel(value) {
  if (value === "klaerung") return "Klärung";
  if (value === "bemerkung") return "Bemerkung / Wiedervorlage";
  return "Rückfrage";
}

function initialForm() {
  return {
    title: "",
    description: "",
    duration_minutes: "",
    case_id: "",
  };
}

function AgendaItemFormFields({ form, setForm, cases }) {
  return (
    <>
      <label>
        <span>Titel</span>
        <input className="input" required value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
      </label>

      <label>
        <span>Dauer in Minuten</span>
        <input
          className="input"
          type="number"
          min="0"
          max="600"
          value={form.duration_minutes}
          onChange={(e) => setForm({ ...form, duration_minutes: e.target.value })}
        />
      </label>

      <label>
        <span>Vorgang</span>
        <select className="input" value={form.case_id} onChange={(e) => setForm({ ...form, case_id: e.target.value })}>
          <option value="">Kein Vorgang</option>
          {cases.map((row) => (
            <option key={row.id} value={row.id}>
              {row.case_number} – {row.title}
            </option>
          ))}
        </select>
      </label>

      <label>
        <span>Beschreibung</span>
        <textarea className="input textarea" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
      </label>
    </>
  );
}

export default function AgendaItemsPage() {
  const [rows, setRows] = useState([]);
  const [cases, setCases] = useState([]);
  const [selected, setSelected] = useState(null);
  const [form, setForm] = useState(initialForm());
  const [query, setQuery] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [modalOpen, setModalOpen] = useState(false);

  async function load() {
    setError("");
    try {
      const [data, caseData] = await Promise.all([api.get("/agenda-items"), api.get("/cases")]);
      setRows(Array.isArray(data) ? data : []);
      setCases(Array.isArray(caseData) ? caseData : []);
    } catch (err) {
      setError(err.message);
    }
  }

  useEffect(() => {
    load();
  }, []);

  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 filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return rows;
    return rows.filter((row) => JSON.stringify(row).toLowerCase().includes(q));
  }, [rows, query]);

  function openCreateModal() {
    setSelected(null);
    setForm(initialForm());
    setMessage("");
    setError("");
    setModalOpen(true);
  }

  function openEditModal(row) {
    setSelected(row);
    setForm({
      title: row.title ?? "",
      description: row.description ?? "",
      duration_minutes: row.duration_minutes != null ? String(row.duration_minutes) : "",
      case_id: row.case_id ? String(row.case_id) : "",
    });
    setMessage("");
    setError("");
    setModalOpen(true);
  }

  function closeModal() {
    setModalOpen(false);
    setSelected(null);
    setForm(initialForm());
    setError("");
  }

  async function submit(e) {
    e.preventDefault();
    setError("");
    setMessage("");

    const payload = {
      title: form.title.trim(),
      description: form.description.trim() || null,
      duration_minutes: form.duration_minutes ? Number(form.duration_minutes) : null,
      case_id: form.case_id ? Number(form.case_id) : null,
    };

    try {
      if (selected?.id) {
        await api.put(`/agenda-items/${selected.id}`, payload);
        setMessage("TOP-Bestandseintrag gespeichert");
      } else {
        await api.post("/agenda-items", payload);
        setMessage("TOP-Bestandseintrag erstellt");
      }
      closeModal();
      await load();
    } catch (err) {
      setError(err.message);
    }
  }

  async function removeItem(id) {
    setError("");
    setMessage("");
    try {
      await api.delete(`/agenda-items/${id}`);
      if (selected?.id === id) closeModal();
      await load();
      setMessage("TOP-Bestandseintrag gelöscht");
    } catch (err) {
      setError(err.message);
    }
  }

  return (
    <>
      <style>{`
        .agenda-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);
        }
        .agenda-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);
        }
        .agenda-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);
        }
        .agenda-modal-header h2 { margin: 0; color: #0f172a; font-size: 1.35rem; }
        .agenda-modal-subtitle { margin: 6px 0 0; color: #64748b; line-height: 1.45; }
        .agenda-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);
        }
        .agenda-modal-close:hover { background: #f1f5f9; }
        .agenda-modal-body { padding: 22px 24px; overflow: auto; background: #ffffff; }
        .agenda-modal-footer { display: flex; justify-content: flex-end; gap: 10px; flex-wrap: wrap; }
        .agenda-followup-note { color: var(--muted); display: block; margin-top: 4px; }
        @media (max-width: 800px) {
          .agenda-modal-backdrop { padding: 12px; align-items: start; }
          .agenda-modal-panel { width: 100%; max-height: calc(100vh - 24px); }
        }
      `}</style>

      <div className="page-grid">
        <SectionCard
          title="TOP-Bestand"
          subtitle="Hier werden nur TOPs ohne Sitzungszuordnung angezeigt. Aus Vorgängen erzeugte TOPs sind über die Vorgangsnummer erkennbar."
          actions={
            <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
              <input className="input search" placeholder="Suchen..." value={query} onChange={(e) => setQuery(e.target.value)} />
              <button className="btn" type="button" onClick={openCreateModal}>
                Neuer TOP-Bestandseintrag
              </button>
            </div>
          }
        >
          {error && !modalOpen ? <div className="alert error">{error}</div> : null}
          {message ? <div className="alert success">{message}</div> : null}
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Vorgang</th>
                  <th>Titel</th>
                  <th>Beschreibung</th>
                  <th>Status</th>
                  <th>Bemerkung</th>
                  <th>Minuten</th>
                  <th>Aktionen</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((row) => (
                  <tr key={row.id} onClick={() => openEditModal(row)}>
                    <td>{row.id}</td>
                    <td>{row.case_number || row.case_id || ""}</td>
                    <td>
                      {row.title}
                      {row.parent_agenda_item_id ? (
                        <>
                          <br />
                          <small className="agenda-followup-note">
                            Folge von TOP {row.parent_agenda_number || row.parent_agenda_item_id}{row.follow_up_source_meeting_number ? ` · Sitzung ${row.follow_up_source_meeting_number}` : ""}
                          </small>
                        </>
                      ) : null}
                    </td>
                    <td>{row.description}</td>
                    <td>{agendaStatusLabel(row.status)}</td>
                    <td>{row.follow_up_note || row.last_return_remark ? <small>{returnTypeLabel(row.follow_up_type || row.last_return_type)}: {row.follow_up_note || row.last_return_remark}</small> : ""}</td>
                    <td>{row.duration_minutes}</td>
                    <td className="row-actions">
                      <button className="mini-btn" type="button" onClick={(e) => { e.stopPropagation(); openEditModal(row); }}>
                        Bearbeiten
                      </button>
                      <button className="mini-btn danger" type="button" onClick={(e) => { e.stopPropagation(); removeItem(row.id); }}>
                        Löschen
                      </button>
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 ? (
                  <tr>
                    <td colSpan={8}>Keine TOP-Bestandseinträge gefunden.</td>
                  </tr>
                ) : null}
              </tbody>
            </table>
          </div>
        </SectionCard>
      </div>

      {modalOpen ? (
        <div className="agenda-modal-backdrop" onMouseDown={closeModal}>
          <div className="agenda-modal-panel" role="dialog" aria-modal="true" aria-labelledby="agenda-modal-title" onMouseDown={(event) => event.stopPropagation()}>
            <div className="agenda-modal-header">
              <div>
                <h2 id="agenda-modal-title">{selected ? "TOP-Bestand bearbeiten" : "Neuen TOP-Bestandseintrag anlegen"}</h2>
                <p className="agenda-modal-subtitle">
                  {selected?.parent_agenda_item_id
                    ? `Folge-TOP zu TOP ${selected.parent_agenda_number || selected.parent_agenda_item_id}${selected.follow_up_source_meeting_number ? ` aus Sitzung ${selected.follow_up_source_meeting_number}` : ""}.`
                    : "Der Eintrag bleibt zunächst ohne Sitzungszuordnung und kann später einer Sitzung hinzugefügt werden."}
                </p>
              </div>
              <button className="agenda-modal-close" type="button" onClick={closeModal} aria-label="Schließen">×</button>
            </div>

            <div className="agenda-modal-body">
              {error ? <div className="alert error">{error}</div> : null}
              <form className="form-grid" onSubmit={submit}>
                <AgendaItemFormFields form={form} setForm={setForm} cases={cases} />
                <div className="agenda-modal-footer">
                  <button className="btn secondary" type="button" onClick={closeModal}>Abbrechen</button>
                  <button className="btn" type="submit">{selected ? "Speichern" : "Erstellen"}</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
