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

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

function formatDateTime(value) {
  if (!value) return "—";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return String(value);
  return date.toLocaleString("de-DE", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function normalizeMeetingsResponse(data) {
  if (Array.isArray(data)) return data;
  if (Array.isArray(data?.items)) return data.items;
  return [];
}

function statusLabel(value) {
  const status = String(value || "").toLowerCase();
  if (status === "geplant") return "Geplant";
  if (status === "gestartet") return "Gestartet";
  if (status === "beendet") return "Beendet";
  if (status === "ungeplant") return "Ungeplant";
  if (status === "neu") return "Neu";
  if (status === "in_bearbeitung") return "In Bearbeitung";
  if (status === "rueckfrage") return "Rückfrage";
  if (status === "abgeschlossen") return "Abgeschlossen";
  return value || "—";
}

export default function DashboardPage() {
  const [stats, setStats] = useState(null);
  const [meetings, setMeetings] = useState([]);
  const [cases, setCases] = useState([]);
  const [notifications, setNotifications] = useState([]);
  const [error, setError] = useState("");

  useEffect(() => {
    let active = true;

    async function load() {
      setError("");
      try {
        const [dashboardData, meetingsData, casesData, notificationsData] = await Promise.all([
          api.get("/dashboard"),
          api.get("/meetings?show_ended=false&page=1&page_size=5"),
          api.get("/cases"),
          api.get("/notifications"),
        ]);

        if (!active) return;

        const nextMeetings = normalizeMeetingsResponse(meetingsData)
          .slice()
          .sort((a, b) => String(a.meeting_date || "").localeCompare(String(b.meeting_date || "")))
          .slice(0, 5);

        const nextCases = (Array.isArray(casesData) ? casesData : [])
          .filter((row) => String(row.status || "") !== "abgeschlossen")
          .slice(0, 5);

        const nextNotifications = (Array.isArray(notificationsData) ? notificationsData : []).slice(0, 5);

        setStats(dashboardData || null);
        setMeetings(nextMeetings);
        setCases(nextCases);
        setNotifications(nextNotifications);
      } catch (err) {
        if (!active) return;
        setError(err.message || "Dashboard konnte nicht geladen werden.");
      }
    }

    load();
    return () => {
      active = false;
    };
  }, []);

  const nextMeeting = useMemo(() => meetings[0] || null, [meetings]);

  const cards = [
    {
      title: "Meine Vorgänge",
      value: stats?.openCases ?? "—",
      hint: stats?.openCases ? `${stats.openCases} offen` : "Keine Daten",
      tone: "blue",
    },
    {
      title: "Nächste Sitzung",
      value: nextMeeting?.meeting_date ? formatDate(nextMeeting.meeting_date) : "—",
      hint: nextMeeting?.title || "Keine Sitzung geplant",
      tone: "green",
    },
    {
      title: "Dringende Fristen",
      value: stats?.urgentDeadlines ?? "—",
      hint: stats?.urgentDeadlines ? "innerhalb 3 Tagen" : "Keine Daten",
      tone: "purple",
    },
    {
      title: "Dokumente",
      value: stats?.documents ?? "—",
      hint: stats?.unreadNotifications ? `${stats.unreadNotifications} neue Hinweise` : "Dokumentenbestand",
      tone: "amber",
    },
  ];

  return (
    <div className="stack dashboard-stack">
      <SectionCard
        title="Dashboard"
        subtitle="Startseite mit den wichtigsten Kennzahlen, Sitzungen, Vorgängen und Benachrichtigungen."
      >
        {error ? <div className="alert error">{error}</div> : null}

        <div className="dashboard-kpi-grid">
          {cards.map((card) => (
            <div key={card.title} className={`dashboard-kpi-card tone-${card.tone}`}>
              <div className="dashboard-kpi-icon" aria-hidden="true" />
              <div className="dashboard-kpi-content">
                <span>{card.title}</span>
                <strong>{card.value}</strong>
                <small>{card.hint}</small>
              </div>
            </div>
          ))}
        </div>
      </SectionCard>

      <div className="dashboard-two-col">
        <SectionCard
          title="Meine nächsten Sitzungen"
          subtitle="Kommende Termine im Überblick"
          actions={<NavLink className="btn secondary" to="/meetings">Alle Sitzungen anzeigen</NavLink>}
        >
          <div className="dashboard-list">
            {meetings.length ? (
              meetings.map((meeting) => (
                <div key={meeting.id} className="dashboard-list-item">
                  <div className="dashboard-date-box">
                    <strong>{formatDate(meeting.meeting_date).slice(0, 5)}</strong>
                    <span>{String(meeting.meeting_date || "").slice(0, 4)}</span>
                  </div>
                  <div className="dashboard-list-main">
                    <strong>{meeting.title || meeting.meeting_number || `Sitzung ${meeting.id}`}</strong>
                    <div className="field-hint">
                      {meeting.meeting_number ? `${meeting.meeting_number} · ` : ""}
                      {meeting.location || "Ort offen"}
                    </div>
                  </div>
                  <span className={`status-chip status-${String(meeting.status || "").toLowerCase()}`}>
                    {statusLabel(meeting.status)}
                  </span>
                </div>
              ))
            ) : (
              <div className="field-hint">Keine kommenden Sitzungen gefunden.</div>
            )}
          </div>
        </SectionCard>

        <SectionCard
          title="Meine offenen Vorgänge"
          subtitle="Nicht abgeschlossene Vorgänge"
          actions={<NavLink className="btn secondary" to="/cases">Alle Vorgänge anzeigen</NavLink>}
        >
          <div className="table-wrap">
            <table className="table dashboard-table">
              <thead>
                <tr>
                  <th>Vorgang</th>
                  <th>Status</th>
                  <th>Priorität</th>
                  <th>Ausschuss</th>
                </tr>
              </thead>
              <tbody>
                {cases.length ? (
                  cases.map((row) => (
                    <tr key={row.id}>
                      <td>
                        <strong>{row.case_number || `V-${row.id}`}</strong>
                        <div className="field-hint">{row.title || "Ohne Titel"}</div>
                      </td>
                      <td>{statusLabel(row.status)}</td>
                      <td>{row.priority || "—"}</td>
                      <td>{row.committee_name || row.department || "—"}</td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={4}>Keine offenen Vorgänge gefunden.</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </SectionCard>
      </div>

      <SectionCard
        title="Aktuelle Benachrichtigungen"
        subtitle="Neueste Hinweise aus dem System"
        actions={<NavLink className="btn secondary" to="/notifications">Alle Benachrichtigungen anzeigen</NavLink>}
      >
        <div className="dashboard-notification-list">
          {notifications.length ? (
            notifications.map((item) => (
              <div key={item.id} className="dashboard-notification-row">
                <div>
                  <strong>{item.title || item.notification_type || "Hinweis"}</strong>
                  <div className="field-hint">
                    {item.entity_type ? `${item.entity_type} · ` : ""}
                    {formatDateTime(item.created_at)}
                  </div>
                </div>
                <span className={`status-chip ${item.is_read ? "status-neutral" : "status-geplant"}`}>
                  {item.is_read ? "Gelesen" : "Neu"}
                </span>
              </div>
            ))
          ) : (
            <div className="field-hint">Keine Benachrichtigungen vorhanden.</div>
          )}
        </div>
      </SectionCard>
    </div>
  );
}
