import React, { useEffect, useMemo, useState } from "react";
import AdminPageHeader from "../../components/admin/AdminPageHeader.jsx";
import DocumentCreationTrendChart from "../../components/admin/DocumentCreationTrendChart.jsx";
import DocumentStatusRadarChart from "../../components/admin/DocumentStatusRadarChart.jsx";
import RecentActivityFeed from "../../components/admin/RecentActivityFeed.jsx";
import { fetchDocuments } from "../../services/swiApi.js";
import { fetchTicketLogs } from "../../services/ticketsApi.js";
import { buildDocumentCreationTrend } from "../../utils/documentCreationTrend.js";
import { documentStatusChartSeries } from "../../utils/documentStatusStats.js";

function StatCard({ label, value, hint, tone = "" }) {
  return (
    <article
      className={`swi-admin-stat-card${tone ? ` swi-admin-stat-card--${tone}` : ""}`}
    >
      <span className="swi-admin-stat-card__value">{value}</span>
      <span className="swi-admin-stat-card__label">{label}</span>
      {hint ? <span className="swi-admin-stat-card__hint">{hint}</span> : null}
    </article>
  );
}

export default function AdminOverviewPage({ onNavigate }) {
  const [loading, setLoading] = useState(true);
  const [documents, setDocuments] = useState([]);
  const [ticketLogs, setTicketLogs] = useState([]);

  const statusSeries = useMemo(
    () => documentStatusChartSeries(documents),
    [documents]
  );

  const creationTrend = useMemo(
    () => buildDocumentCreationTrend(documents, 12),
    [documents]
  );

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [docs, logs] = await Promise.all([
          fetchDocuments(),
          fetchTicketLogs({ limit: 40 }).catch(() => []),
        ]);
        if (!cancelled) {
          setDocuments(Array.isArray(docs) ? docs : []);
          setTicketLogs(Array.isArray(logs) ? logs : []);
        }
      } catch {
        if (!cancelled) {
          setDocuments([]);
          setTicketLogs([]);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <div className="swi-admin-overview">
      <AdminPageHeader
        title="Admin overview"
        subtitle="SWI document status and creation analytics."
      />

      <section
        className="swi-admin-stat-grid swi-admin-stat-grid--status"
        aria-label="Document status summary"
      >
        {statusSeries.map((item) => (
          <StatCard
            key={item.statusId}
            label={item.label}
            value={loading ? "…" : item.value}
            hint="SWI documents in this status"
            tone={item.tone}
          />
        ))}
      </section>

      <div className="swi-admin-overview-charts">
        <DocumentStatusRadarChart series={statusSeries} loading={loading} />
        <DocumentCreationTrendChart data={creationTrend} loading={loading} />
      </div>

      <RecentActivityFeed
        documents={documents}
        ticketLogs={ticketLogs}
        loading={loading}
        onViewAll={onNavigate}
      />
    </div>
  );
}
