import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
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 value;
  return date.toLocaleString("de-DE");
}

function getTargetInfo(row) {
  const entityType = String(row.entity_type || "").toLowerCase();
  const entityId = row.entity_id;

  switch (entityType) {
    case "case":
    case "br_case":
    case "vorgang":
      return {
        label: entityId ? `Vorgang ${entityId}` : "Vorgang",
        path: entityId ? `/cases?open=${entityId}` : "/cases",
      };
    case "decision":
    case "beschluss":
      return {
        label: entityId ? `Beschluss ${entityId}` : "Beschluss",
        path: entityId ? `/decisions?open=${entityId}` : "/decisions",
      };
    case "meeting":
    case "sitzung":
      return {
        label: entityId ? `Sitzung ${entityId}` : "Sitzung",
        path: entityId ? `/meetings?open=${entityId}` : "/meetings",
      };
    case "document":
    case "dokument":
      return {
        label: entityId ? `Dokument ${entityId}` : "Dokument",
        path: entityId ? `/documents?open=${entityId}` : "/documents",
      };
    default:
      return {
        label: row.entity_type && entityId ? `${row.entity_type} ${entityId}` : "—",
        path: null,
      };
  }
}

export default function NotificationsPage() {
  const navigate = useNavigate();

  const [rows, setRows] = useState([]);
  const [query, setQuery] = useState("");
  const [onlyMine, setOnlyMine] = useState(true);
  const [unreadFirst, setUnreadFirst] = useState(true);
  const [loading, setLoading] = useState(false);
  const [busyId, setBusyId] = useState(null);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  async function load({
    nextQuery = query,
    nextOnlyMine = onlyMine,
    nextUnreadFirst = unreadFirst,
  } = {}) {
    setError("");
    setLoading(true);

    try {
      const params = new URLSearchParams({
        only_mine: nextOnlyMine ? "true" : "false",
        unread_first: nextUnreadFirst ? "true" : "false",
      });

      if (String(nextQuery || "").trim()) {
        params.set("q", nextQuery.trim());
      }

      const data = await api.get(`/notifications?${params.toString()}`);
      setRows(Array.isArray(data) ? data : []);
    } catch (err) {
      setError(err.message || "Benachrichtigungen konnten nicht geladen werden.");
    } finally {
      setLoading(false);
    }
  }

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

  useEffect(() => {
    const timer = window.setTimeout(() => {
      load({ nextQuery: query });
    }, 250);

    return () => window.clearTimeout(timer);
  }, [query]);

  async function markRead(id) {
    setBusyId(id);
    setError("");
    setMessage("");

    try {
      await api.post(`/notifications/${id}/read`, {});
      await load();
      setMessage("Benachrichtigung als gelesen markiert");
    } catch (err) {
      setError(err.message || "Benachrichtigung konnte nicht aktualisiert werden.");
    } finally {
      setBusyId(null);
    }
  }

  async function markAllRead() {
    setBusyId("all");
    setError("");
    setMessage("");

    try {
      const result = await api.post("/notifications/mark-all-read", {});
      await load();
      setMessage(`${result?.count ?? 0} Benachrichtigungen als gelesen markiert`);
    } catch (err) {
      setError(err.message || "Benachrichtigungen konnten nicht aktualisiert werden.");
    } finally {
      setBusyId(null);
    }
  }

  async function openTarget(row) {
    const target = getTargetInfo(row);

    if (!row.is_read) {
      try {
        await api.post(`/notifications/${row.id}/read`, {});
      } catch {
        // Navigation soll trotzdem möglich bleiben
      }
    }

    await load();

    if (target.path) {
      navigate(target.path);
    }
  }

  async function removeNotification(id) {
    setBusyId(id);
    setError("");
    setMessage("");

    try {
      await api.delete(`/notifications/${id}`);
      await load();
      setMessage("Benachrichtigung gelöscht");
    } catch (err) {
      setError(err.message || "Benachrichtigung konnte nicht gelöscht werden.");
    } finally {
      setBusyId(null);
    }
  }

  return (
    <SectionCard
      title="Benachrichtigungen"
      subtitle="Filterbar nach eigenen Benachrichtigungen. Ungelesene können bevorzugt oben angezeigt und direkt geöffnet werden."
      actions={
        <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
          <label style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <input
              type="checkbox"
              checked={onlyMine}
              onChange={(e) => setOnlyMine(e.target.checked)}
            />
            <span>Nur meine Benachrichtigungen</span>
          </label>

          <label style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <input
              type="checkbox"
              checked={unreadFirst}
              onChange={(e) => setUnreadFirst(e.target.checked)}
            />
            <span>Ungelesen zuerst</span>
          </label>

          <input
            className="input search"
            placeholder="Suchen..."
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />

          <button
            className="btn secondary"
            type="button"
            onClick={markAllRead}
            disabled={busyId === "all"}
          >
            Alle als gelesen
          </button>
        </div>
      }
    >
      {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>Titel</th>
              <th>Typ</th>
              <th>Ziel</th>
              <th>Benutzer</th>
              <th>Status</th>
              <th>Zeit</th>
              <th>Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row) => {
              const target = getTargetInfo(row);

              return (
                <tr
                  key={row.id}
                  style={{
                    fontWeight: row.is_read ? "normal" : 600,
                    opacity: row.is_read ? 0.8 : 1,
                  }}
                >
                  <td>{row.id}</td>
                  <td>{row.title}</td>
                  <td>{row.notification_type}</td>
                  <td>
                    {target.path ? (
                      <button
                        type="button"
                        className="mini-btn"
                        onClick={() => openTarget(row)}
                      >
                        {target.label}
                      </button>
                    ) : (
                      target.label
                    )}
                  </td>
                  <td>{row.user_name || row.user_id || ""}</td>
                  <td>{row.is_read ? "gelesen" : "ungelesen"}</td>
                  <td>{formatDateTime(row.created_at)}</td>
                  <td className="row-actions">
                    {!row.is_read ? (
                      <button
                        className="mini-btn"
                        type="button"
                        disabled={busyId === row.id}
                        onClick={() => markRead(row.id)}
                      >
                        Als gelesen
                      </button>
                    ) : null}

                    {target.path ? (
                      <button
                        className="mini-btn"
                        type="button"
                        onClick={() => openTarget(row)}
                      >
                        Öffnen
                      </button>
                    ) : null}

                    <button
                      className="mini-btn danger"
                      type="button"
                      disabled={busyId === row.id}
                      onClick={() => removeNotification(row.id)}
                    >
                      Löschen
                    </button>
                  </td>
                </tr>
              );
            })}

            {!loading && !rows.length ? (
              <tr>
                <td colSpan={8}>Keine Benachrichtigungen gefunden</td>
              </tr>
            ) : null}
          </tbody>
        </table>
      </div>
    </SectionCard>
  );
}
