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

function emptyForm() {
  return {
    entity_type: "agenda_item",
    entity_id: "",
    comment_text: "",
    visibility: "intern",
  };
}

function dateTime(value) {
  if (!value) return "";
  return new Intl.DateTimeFormat("de-DE", {
    dateStyle: "short",
    timeStyle: "short",
  }).format(new Date(value));
}

function dateOnly(value) {
  if (!value) return "";
  return new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(new Date(value));
}

function visibilityLabel(value) {
  if (value === "vertraulich") return "Vertraulich";
  return "Intern";
}

function statusLabel(value) {
  const labels = {
    geplant: "Geplant",
    ungeplant: "Ungeplant",
    gestartet: "Gestartet",
    beendet: "Beendet",
    in_bearbeitung: "In Bearbeitung",
    rueckfrage: "Rückfrage",
    klaerung: "Klärung",
    abgeschlossen: "Abgeschlossen",
  };
  return labels[value] || value || "Offen";
}

function agendaLabel(item) {
  if (!item) return "";
  const parts = [];
  if (item.meeting_number) parts.push(`Sitzung ${item.meeting_number}`);
  if (item.agenda_number) parts.push(`TOP ${item.agenda_number}`);
  if (item.case_number) parts.push(item.case_number);
  const prefix = parts.length ? `${parts.join(" · ")} · ` : "";
  return `${prefix}${item.title || "Ohne Titel"}`;
}

export default function CommentsPage() {
  const [comments, setComments] = useState([]);
  const [openAgendaItems, setOpenAgendaItems] = useState([]);
  const [form, setForm] = useState(emptyForm());
  const [selected, setSelected] = useState(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [agendaFilter, setAgendaFilter] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function load() {
    setLoading(true);
    setError("");
    try {
      const [commentRows, agendaRows] = await Promise.all([
        api.get("/comments"),
        api.get("/comments/open-agenda-items"),
      ]);
      setComments(Array.isArray(commentRows) ? commentRows : []);
      setOpenAgendaItems(Array.isArray(agendaRows) ? agendaRows : []);
    } catch (err) {
      setError(err.message || "Kommentare konnten nicht geladen werden.");
    } finally {
      setLoading(false);
    }
  }

  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 agendaOptions = useMemo(() => {
    const options = [...openAgendaItems];
    if (selected?.entity_type === "agenda_item" && selected.entity_id && !options.some((item) => String(item.id) === String(selected.entity_id))) {
      options.unshift({
        id: selected.entity_id,
        title: selected.agenda_item_title || `TOP ${selected.entity_id}`,
        agenda_number: selected.agenda_number,
        meeting_number: selected.meeting_number,
        meeting_date: selected.meeting_date,
        meeting_status: selected.meeting_status,
        case_number: selected.case_number,
        decision_number: selected.decision_number,
        decision_status: selected.decision_status,
      });
    }
    return options;
  }, [openAgendaItems, selected]);

  const filteredComments = useMemo(() => {
    const text = query.trim().toLowerCase();
    return comments.filter((comment) => {
      if (agendaFilter && String(comment.entity_id) !== String(agendaFilter)) return false;
      if (!text) return true;
      return JSON.stringify(comment).toLowerCase().includes(text);
    });
  }, [comments, query, agendaFilter]);

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

  function openCreateModal() {
    setSelected(null);
    setForm({ ...emptyForm(), entity_id: agendaFilter || "" });
    setMessage("");
    setError("");
    setModalOpen(true);
  }

  function openEditModal(comment) {
    setSelected(comment);
    setForm({
      entity_type: comment.entity_type || "agenda_item",
      entity_id: comment.entity_id ? String(comment.entity_id) : "",
      comment_text: comment.comment_text || "",
      visibility: comment.visibility || "intern",
    });
    setMessage("");
    setError("");
    setModalOpen(true);
  }

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

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

    if (!form.entity_id) {
      setError("Bitte einen offenen TOP auswählen.");
      return;
    }

    const payload = {
      entity_type: "agenda_item",
      entity_id: Number(form.entity_id),
      comment_text: form.comment_text,
      visibility: form.visibility || "intern",
    };

    try {
      if (selected?.id) {
        await api.put(`/comments/${selected.id}`, payload);
        setMessage("Kommentar gespeichert.");
      } else {
        await api.post("/comments", payload);
        setMessage("Kommentar angelegt.");
      }
      closeModal();
      await load();
    } catch (err) {
      setError(err.message || "Kommentar konnte nicht gespeichert werden.");
    }
  }

  async function remove(comment) {
    if (!window.confirm("Kommentar löschen?")) return;
    setMessage("");
    setError("");
    try {
      await api.delete(`/comments/${comment.id}`);
      setMessage("Kommentar gelöscht.");
      if (selected?.id === comment.id) closeModal();
      await load();
    } catch (err) {
      setError(err.message || "Kommentar konnte nicht gelöscht werden.");
    }
  }

  return (
    <>
      <style>{`
        .comments-grid { display: grid; gap: 18px; }
        .comments-toolbar { display: flex; gap: 10px; flex-wrap: wrap; align-items: end; margin-bottom: 14px; }
        .comments-toolbar label { min-width: 220px; }
        .comments-badge { display: inline-flex; align-items: center; border-radius: 999px; padding: 4px 9px; font-size: .82rem; font-weight: 800; background: rgba(37,99,235,.1); color: #1d4ed8; }
        .comments-badge.confidential { background: #fff7ed; color: #9a3412; }
        .comments-muted { color: var(--muted); }
        .comments-text { white-space: pre-wrap; line-height: 1.5; }
        .comments-form-note { margin: 0; color: var(--muted); line-height: 1.45; }
        .comments-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);
        }
        .comments-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);
        }
        .comments-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);
        }
        .comments-modal-header h2 { margin: 0; color: #0f172a; font-size: 1.35rem; }
        .comments-modal-subtitle { margin: 6px 0 0; color: #64748b; line-height: 1.45; }
        .comments-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);
        }
        .comments-modal-close:hover { background: #f1f5f9; }
        .comments-modal-body { padding: 22px 24px; overflow: auto; background: #ffffff; }
        .comments-modal-footer { display: flex; justify-content: flex-end; gap: 10px; flex-wrap: wrap; }
        @media (max-width: 800px) {
          .comments-modal-backdrop { padding: 12px; align-items: start; }
          .comments-modal-panel { width: 100%; max-height: calc(100vh - 24px); }
        }
      `}</style>

      <div className="comments-grid">
        {error && !modalOpen ? <div className="alert error">{error}</div> : null}
        {message ? <div className="alert success">{message}</div> : null}

        <SectionCard
          title="Kommentare"
          subtitle="Kommentare können mit offenen TOPs aus dem TOP-Bestand verknüpft werden. Bereits einer Sitzung zugeordnete oder abgeschlossene TOPs werden in der Auswahl nicht angeboten."
          actions={
            <div className="row-actions">
              <button className="btn" type="button" onClick={openCreateModal}>Kommentar anlegen</button>
              <button className="btn secondary" type="button" onClick={load} disabled={loading}>{loading ? "Lade…" : "Aktualisieren"}</button>
            </div>
          }
        >
          <div className="comments-toolbar">
            <label>
              <span>Suchen</span>
              <input className="input" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Kommentar, TOP, Sitzung …" />
            </label>
            <label>
              <span>TOP filtern</span>
              <select className="input" value={agendaFilter} onChange={(event) => setAgendaFilter(event.target.value)}>
                <option value="">Alle offenen TOPs im TOP-Bestand</option>
                {openAgendaItems.map((item) => (
                  <option key={item.id} value={item.id}>{agendaLabel(item)}</option>
                ))}
              </select>
            </label>
          </div>
        </SectionCard>

        <SectionCard title="Kommentarliste" subtitle="Anzeige der vorhandenen Kommentare mit TOP-Bezug.">
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr>
                  <th>TOP</th>
                  <th>Kommentar</th>
                  <th>Sichtbarkeit</th>
                  <th>Kommentar von</th>
                  <th>Aktionen</th>
                </tr>
              </thead>
              <tbody>
                {filteredComments.map((comment) => (
                  <tr key={comment.id} onClick={() => openEditModal(comment)}>
                    <td>
                      <strong>{comment.agenda_item_title || `${comment.entity_type} #${comment.entity_id}`}</strong>
                      <br />
                      <small className="comments-muted">
                        {comment.meeting_number ? `Sitzung ${comment.meeting_number}` : "TOP-Bestand"}
                        {comment.agenda_number ? ` · TOP ${comment.agenda_number}` : ""}
                        {comment.meeting_date ? ` · ${dateOnly(comment.meeting_date)}` : ""}
                        {comment.decision_status ? ` · ${statusLabel(comment.decision_status)}` : ""}
                      </small>
                    </td>
                    <td className="comments-text">{comment.comment_text}</td>
                    <td><span className={`comments-badge ${comment.visibility === "vertraulich" ? "confidential" : ""}`}>{visibilityLabel(comment.visibility)}</span></td>
                    <td><strong>Kommentar von: {comment.author_name || "—"}</strong><br /><small>{dateTime(comment.created_at)}</small></td>
                    <td>
                      <div className="row-actions">
                        <button className="mini-btn" type="button" onClick={(event) => { event.stopPropagation(); openEditModal(comment); }}>Bearbeiten</button>
                        <button className="mini-btn danger" type="button" onClick={(event) => { event.stopPropagation(); remove(comment); }}>Löschen</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!filteredComments.length ? <tr><td colSpan="5">Noch keine Kommentare vorhanden.</td></tr> : null}
              </tbody>
            </table>
          </div>
        </SectionCard>
      </div>

      {modalOpen ? (
        <div className="comments-modal-backdrop" onMouseDown={closeModal}>
          <div className="comments-modal-panel" role="dialog" aria-modal="true" aria-labelledby="comments-modal-title" onMouseDown={(event) => event.stopPropagation()}>
            <div className="comments-modal-header">
              <div>
                <h2 id="comments-modal-title">{selected ? "Kommentar bearbeiten" : "Kommentar anlegen"}</h2>
                <p className="comments-modal-subtitle">Wähle einen offenen TOP aus dem TOP-Bestand aus und erfasse die Bemerkung als Kommentar.</p>
              </div>
              <button className="comments-modal-close" type="button" onClick={closeModal} aria-label="Schließen">×</button>
            </div>

            <div className="comments-modal-body">
              {error ? <div className="alert error">{error}</div> : null}
              <form className="form-grid" onSubmit={submit}>
                <label>
                  <span>TOP</span>
                  <select className="input" required value={form.entity_id} onChange={(event) => update("entity_id", event.target.value)}>
                    <option value="">Offenen TOP aus TOP-Bestand auswählen</option>
                    {agendaOptions.map((item) => (
                      <option key={item.id} value={item.id}>{agendaLabel(item)}</option>
                    ))}
                  </select>
                </label>

                <label>
                  <span>Sichtbarkeit</span>
                  <select className="input" value={form.visibility} onChange={(event) => update("visibility", event.target.value)}>
                    <option value="intern">Intern</option>
                    <option value="vertraulich">Vertraulich</option>
                  </select>
                </label>

                <label>
                  <span>Kommentar</span>
                  <textarea className="input textarea" required value={form.comment_text} onChange={(event) => update("comment_text", event.target.value)} />
                </label>

                <p className="comments-form-note">
                  Hinweis: Die Auswahl entspricht dem TOP-Bestand aus „TOPs“ und enthält nur nicht erledigte TOPs, die noch keiner Sitzung zugeordnet sind. Bereits vorhandene Kommentare bleiben sichtbar, sofern deine Rolle darauf zugreifen darf.
                </p>

                <div className="comments-modal-footer">
                  <button className="btn secondary" type="button" onClick={closeModal}>Abbrechen</button>
                  <button className="btn" type="submit">{selected ? "Kommentar speichern" : "Kommentar anlegen"}</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
