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

function formatDateTime(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return String(value);
  return date.toLocaleString("de-DE");
}

export default function ReportsPage() {
  const [rows, setRows] = useState([]);
  const [query, setQuery] = useState("");
  const [error, setError] = useState("");
  const [message, setMessage] = useState("");

  async function load() {
    setError("");
    try {
      const documents = await api.get("/documents");
      const filtered = (Array.isArray(documents) ? documents : []).filter((row) => {
        const type = String(row.document_type || "").toLowerCase();
        return type.includes("bericht") || type.includes("report") || type.includes("protokoll");
      });
      setRows(filtered);
    } catch (err) {
      setError(err.message || "Reports konnten nicht geladen werden.");
    }
  }

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

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return rows;
    return rows.filter((row) => JSON.stringify(row).toLowerCase().includes(q));
  }, [rows, query]);

  async function removeItem(id) {
    setError("");
    setMessage("");
    try {
      await api.delete(`/documents/${id}`);
      await load();
      setMessage("Report gelöscht");
    } catch (err) {
      setError(err.message || "Report konnte nicht gelöscht werden.");
    }
  }

  return (
    <SectionCard
      title="Reports"
      subtitle="Berichte, Protokolle und reportbezogene Dokumente im Überblick."
      actions={
        <input
          className="input search"
          placeholder="Reports durchsuchen..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
      }
    >
      {error ? <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>Dokument-Nr.</th>
              <th>Titel</th>
              <th>Art</th>
              <th>Vertraulichkeit</th>
              <th>Sitzung</th>
              <th>Hochgeladen</th>
              <th>Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {filtered.length ? (
              filtered.map((row) => (
                <tr key={row.id}>
                  <td>{row.id}</td>
                  <td>{row.document_number || ""}</td>
                  <td>{row.title || ""}</td>
                  <td>{row.document_type || ""}</td>
                  <td>{row.confidentiality_level || ""}</td>
                  <td>{row.meeting_id || ""}</td>
                  <td>{formatDateTime(row.uploaded_at)}</td>
                  <td className="row-actions">
                    <button className="mini-btn danger" type="button" onClick={() => removeItem(row.id)}>
                      Löschen
                    </button>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={8}>Keine Reports gefunden</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </SectionCard>
  );
}
