import React, { useEffect, useMemo, useState } from "react";
import UserStatCard from "../../components/user/UserStatCard.jsx";
import UserSwiDocumentList from "../../components/user/UserSwiDocumentList.jsx";
import { SWI_DOCUMENT_STATUS } from "../../constants/swiDocumentStatus.js";
import { useAuth } from "../../context/AuthContext.jsx";
import { getApiErrorMessage } from "../../utils/apiError.js";
import { authUserId } from "../../utils/jwtPayload.js";
import { userSwiSummary } from "../../utils/userSwiStats.js";

/**
 * @param {{
 *   assignments?: object[],
 *   loading?: boolean,
 *   onRefresh?: () => Promise<unknown>,
 *   isUnread?: (row: object) => boolean,
 *   onMarkAllRead?: () => void,
 *   onMarkRead?: (row: object) => void,
 *   onOpenForm?: (documentId: number, documentNumber: number) => void,
 *   onViewSubmission?: (documentId: number, documentNumber: number) => void,
 *   initialFilter?: string,
 * }} props
 */
export default function AssignedSwisPage({
  assignments = [],
  loading = false,
  onRefresh,
  isUnread,
  onMarkAllRead,
  onMarkRead,
  onOpenForm,
  onViewSubmission,
  initialFilter = "all",
}) {
  const { auth } = useAuth();
  const [error, setError] = useState("");
  const [filter, setFilter] = useState(initialFilter);

  useEffect(() => {
    setFilter(initialFilter);
  }, [initialFilter]);

  useEffect(() => {
    onMarkAllRead?.();
  }, []); // Mark assignments seen when user opens this page

  const unreadCount = useMemo(
    () => (isUnread ? assignments.filter(isUnread).length : 0),
    [assignments, isUnread]
  );

  const awaitingAction = useMemo(
    () =>
      assignments.filter(
        (row) =>
          Number(row.document_status_id) === SWI_DOCUMENT_STATUS.ASSIGNED
      ),
    [assignments]
  );

  const summary = useMemo(() => userSwiSummary(assignments), [assignments]);

  const filtered = useMemo(() => {
    if (filter === "new" && isUnread) {
      return assignments.filter(isUnread);
    }
    if (filter === "awaiting") return awaitingAction;
    if (filter === "in-progress") {
      return assignments.filter(
        (row) =>
          Number(row.document_status_id) === SWI_DOCUMENT_STATUS.IN_PROGRESS
      );
    }
    if (filter === "completed") {
      return assignments.filter(
        (row) =>
          Number(row.document_status_id) === SWI_DOCUMENT_STATUS.COMPLETED
      );
    }
    return assignments;
  }, [assignments, awaitingAction, filter, isUnread]);

  const handleRefresh = async () => {
    if (!onRefresh) return;
    setError("");
    try {
      await onRefresh();
    } catch (e) {
      setError(getApiErrorMessage(e, "Could not refresh assignments."));
    }
  };

  if (loading) {
    return <p className="swi-muted">Loading assigned 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">Assigned SWIs</h1>
          <p className="portal-page-subtitle">
            SWI documents your admin assigned to you. New assignments appear here
            and in the notification bell.
          </p>
        </div>
        {onRefresh ? (
          <div className="portal-page-header__actions">
            <button type="button" className="swi-btn swi-btn--ghost" onClick={handleRefresh}>
              Refresh
            </button>
          </div>
        ) : null}
      </header>

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

      <section
        className="swi-user-stat-grid swi-user-stat-grid--compact"
        aria-label="Assigned SWI summary"
      >
        <UserStatCard
          label="Total assigned"
          value={summary.total}
          tone="assigned"
        />
        <UserStatCard
          label="New"
          value={unreadCount}
          hint="Not yet opened from notifications"
          tone="opened"
        />
        <UserStatCard
          label="Awaiting start"
          value={awaitingAction.length}
          hint="Status: Assigned"
          tone="assigned"
        />
        <UserStatCard
          label="In progress"
          value={summary.inProgress}
          tone="in-progress"
        />
      </section>

      <section className="swi-panel">
        <div className="swi-user-status-filter" role="tablist" aria-label="Filter assigned SWIs">
          {[
            { id: "all", label: "All", count: assignments.length },
            { id: "new", label: "New", count: unreadCount },
            { id: "awaiting", label: "Awaiting start", count: awaitingAction.length },
            { id: "in-progress", label: "In progress", count: summary.inProgress },
            { id: "completed", label: "Completed", count: summary.completed },
          ].map((tab) => (
            <button
              key={tab.id}
              type="button"
              role="tab"
              aria-selected={filter === tab.id}
              className={`swi-user-status-filter__btn${filter === tab.id ? " is-active" : ""}`}
              onClick={() => setFilter(tab.id)}
            >
              {tab.label}
              <span className="swi-user-status-filter__count">{tab.count}</span>
            </button>
          ))}
        </div>

        <UserSwiDocumentList
          documents={filtered}
          currentUserId={authUserId(auth)}
          onOpenForm={(documentId, documentNumber) => {
            const row = assignments.find(
              (item) =>
                item.document_id === documentId &&
                item.document_number === documentNumber
            );
            if (row) onMarkRead?.(row);
            onOpenForm?.(documentId, documentNumber);
          }}
          onViewSubmission={onViewSubmission}
          isUnread={isUnread}
          emptyMessage={
            filter === "all"
              ? "No SWIs have been assigned to you yet."
              : "No SWIs match this filter."
          }
        />
      </section>
    </div>
  );
}
