import React, { useCallback, useEffect, useMemo, useState } from "react";
import UserStatCard from "../../components/user/UserStatCard.jsx";
import UserSwiDocumentList from "../../components/user/UserSwiDocumentList.jsx";
import UserSwiStatusFilter from "../../components/user/UserSwiStatusFilter.jsx";
import { useAuth } from "../../context/AuthContext.jsx";
import { fetchMyAssignments } from "../../services/swiApi.js";
import { getApiErrorMessage } from "../../utils/apiError.js";
import { authUserId } from "../../utils/jwtPayload.js";
import {
  filterDocumentsByStatus,
  userSwiStatusSeries,
  userSwiSummary,
} from "../../utils/userSwiStats.js";

export default function MySwisPage({
  onOpenForm,
  onViewSubmission,
  initialStatusFilter = "all",
}) {
  const { auth } = useAuth();
  const [documents, setDocuments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [statusFilter, setStatusFilter] = useState(initialStatusFilter);

  useEffect(() => {
    setStatusFilter(initialStatusFilter);
  }, [initialStatusFilter]);

  const load = useCallback(async () => {
    setError("");
    const rows = await fetchMyAssignments();
    setDocuments(Array.isArray(rows) ? rows : []);
  }, []);

  useEffect(() => {
    load()
      .catch((e) =>
        setError(getApiErrorMessage(e, "Could not load your SWIs."))
      )
      .finally(() => setLoading(false));
  }, [load]);

  const summary = useMemo(() => userSwiSummary(documents), [documents]);
  const statusSeries = useMemo(
    () => userSwiStatusSeries(documents),
    [documents]
  );
  const filtered = useMemo(
    () => filterDocumentsByStatus(documents, statusFilter),
    [documents, statusFilter]
  );

  if (loading) {
    return <p className="swi-muted">Loading your SWIs…</p>;
  }

  return (
    <div className="swi-user-page">
      <header className="portal-page-header portal-page-header--solo">
        <div className="portal-page-header__text">
          <h1 className="portal-page-title">My SWIs</h1>
          <p className="portal-page-subtitle">
            Standard work instructions assigned to you. Open a document to fill
            or review the form.
          </p>
        </div>
      </header>

      {error ? (
        <div className="swi-error" role="alert">
          {error}
        </div>
      ) : null}

      <section
        className="swi-user-stat-grid swi-user-stat-grid--compact"
        aria-label="My SWI counts"
      >
        <UserStatCard label="Total" value={summary.total} tone="assigned" />
        <UserStatCard
          label="Pending"
          value={summary.pending}
          hint="Opened, assigned, or in progress"
          tone="opened"
        />
        <UserStatCard
          label="In progress"
          value={summary.inProgress}
          tone="in-progress"
        />
        <UserStatCard
          label="Completed"
          value={summary.completed}
          tone="completed"
        />
      </section>

      <section className="swi-panel">
        <UserSwiStatusFilter
          series={statusSeries}
          activeStatusId={statusFilter}
          onSelect={setStatusFilter}
        />

        <UserSwiDocumentList
          documents={filtered}
          currentUserId={authUserId(auth)}
          onOpenForm={onOpenForm}
          onViewSubmission={onViewSubmission}
          emptyMessage={
            statusFilter === "all"
              ? "No SWIs assigned to you yet."
              : "No SWIs in this status."
          }
        />
      </section>
    </div>
  );
}
