import React, { useCallback, useEffect, useState } from "react";
import api from "../../services/api.js";
import PortalShell from "../layout/PortalShell.jsx";
import StatCards from "./dashboard/StatCards.jsx";
import DashboardOverviewToolbar from "./dashboard/DashboardOverviewToolbar.jsx";
import DowntimeTrend from "./analytics/DowntimeTrend.jsx";
import SWIDocumentTable from "./documents/SWIDocumentTable.jsx";
import ApprovalQueue from "./approvals/ApprovalQueue.jsx";
import NewDocumentModal from "./forms/NewDocumentModal.jsx";
import DocumentDetailDrawer from "./detail/DocumentDetailDrawer.jsx";

const SWIDashboard = () => {
  const [tab, setTab] = useState("overview");
  const [range, setRange] = useState("30");
  const [dashboard, setDashboard] = useState(null);
  const [documents, setDocuments] = useState([]);
  const [approvals, setApprovals] = useState([]);
  const [error, setError] = useState("");
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedId, setSelectedId] = useState(null);

  const refreshDashboard = useCallback(async () => {
    const { data } = await api.get("/swi/dashboard");
    setDashboard(data);
  }, []);

  const refreshDocuments = useCallback(async () => {
    const { data } = await api.get("/swi/documents");
    setDocuments(data);
  }, []);

  const refreshApprovals = useCallback(async () => {
    const { data } = await api.get("/swi/approvals/pending");
    setApprovals(data);
  }, []);

  const loadAll = useCallback(async () => {
    setError("");
    try {
      await Promise.all([refreshDashboard(), refreshDocuments(), refreshApprovals()]);
    } catch (e) {
      setError(
        e.response?.data?.error ||
          e.message ||
          "Could not reach the API. Start the backend and apply the MySQL schema."
      );
    }
  }, [refreshApprovals, refreshDashboard, refreshDocuments]);

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

  const seedDemo = async () => {
    try {
      await api.post("/swi/seed-demo");
      await loadAll();
    } catch (e) {
      setError(e.response?.data?.error || e.message);
    }
  };

  const onSign = async (stepId, action) => {
    try {
      await api.post(`/swi/approvals/${stepId}/sign`, { action });
      await loadAll();
    } catch (e) {
      setError(e.response?.data?.error || e.message);
    }
  };

  const stats = dashboard || {
    total: 0,
    pending: 0,
    approved: 0,
    overdue: 0,
  };

  const pageHeader = (title, subtitle, actionsRight = null) => (
    <header className={`portal-page-header${actionsRight ? "" : " portal-page-header--solo"}`}>
      <div className="portal-page-header__text">
        <h1 className="portal-page-title">{title}</h1>
        <p className="portal-page-subtitle">{subtitle}</p>
      </div>
      {actionsRight ? <div className="portal-page-header__actions">{actionsRight}</div>
       : null}
    </header>
  );

  return (
    <PortalShell activeNav={tab} onNavigate={setTab}>
      <div className="portal-page">
        {error ? (
          <div className="swi-error" role="alert">
            {error}
          </div>
        ) : null}

        {tab === "overview" ? (
          <>
            {pageHeader(
              "SWI / SOP dashboard",
              "Monitor document control, approvals, and review compliance across contracts and activities.",
              null
            )}
            <DashboardOverviewToolbar
              range={range}
              onRangeChange={setRange}
              approvedCount={stats.approved}
              overdueCount={stats.overdue}
              onViewActivityLog={() => setTab("approvals")}
              onOverdueAction={() => setTab("documents")}
            />
            <div className="portal-dashboard-secondary-actions">
              <button type="button" className="swi-btn" onClick={loadAll}>
                Refresh
              </button>
              <button type="button" className="swi-btn" onClick={seedDemo}>
                Load sample data
              </button>
            </div>
            <StatCards stats={stats} onQuickAdd={() => setModalOpen(true)} />
            <div className="swi-panels portal-panels">
              <DowntimeTrend downtimeTrend={dashboard?.downtimeTrend || []} />
              <div className="swi-panel portal-side-card">
                <h3 className="swi-panel__title portal-panel__title">Status distribution</h3>
                <p className="portal-panel__desc">Documents by workflow state.</p>
                {dashboard?.byStatus?.length ? (
                  <ul className="swi-version-list">
                    {dashboard.byStatus.map((r) => (
                      <li key={r.status} className="portal-status-row">
                        <span className="portal-status-row__name">{r.status}</span>
                        <span className="portal-status-row__count">{r.count}</span>
                      </li>
                    ))}
                  </ul>
                ) : (
                  <p className="swi-muted">No data yet.</p>
                )}
              </div>
            </div>
          </>
        ) : null}

        {tab === "documents" ? (
          <>
            {pageHeader(
              "Document registry",
              "Standard work instructions and SOPs with version history, reviews, and linked media.",
              (
                <>
                  <button type="button" className="swi-btn" onClick={loadAll}>
                    Refresh
                  </button>
                  <button
                    type="button"
                    className="swi-btn swi-btn--primary"
                    onClick={() => setModalOpen(true)}
                  >
                    New SWI / SOP
                  </button>
                </>
              )
            )}
            <p className="portal-page-lead swi-muted">
              Select a row to open the detail drawer — edit content, add versions, upload photos or
              video, and process approval steps.
            </p>
            <SWIDocumentTable
              documents={documents}
              selectedId={selectedId}
              onSelect={(d) => setSelectedId(Number(d.id))}
            />
          </>
        ) : null}

        {tab === "approvals" ? (
          <>
            {pageHeader(
              "Approvals & activity",
              "Pending electronic signatures and multi-level routing (demo approvers).",
              (
                <button type="button" className="swi-btn" onClick={loadAll}>
                  Refresh queue
                </button>
              )
            )}
            <div className="swi-panel">
              <h3 className="swi-panel__title portal-panel__title">Pending signatures</h3>
              <p className="swi-panel__subtitle">
                Approvers are assigned automatically from your matrix (illustrative data).
              </p>
              <ApprovalQueue items={approvals} onSign={onSign} />
            </div>
          </>
        ) : null}
      </div>

      <NewDocumentModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        onCreated={loadAll}
      />

      <DocumentDetailDrawer
        documentId={selectedId}
        onClose={() => setSelectedId(null)}
        onRefreshList={loadAll}
      />
    </PortalShell>
  );
};

export default SWIDashboard;
