import React, { 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 { fetchMyLocationDocuments } 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 MyLocationSwisPage({ onOpenForm, onViewSubmission }) {
  const { auth } = useAuth();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [locationName, setLocationName] = useState(null);
  const [documents, setDocuments] = useState([]);
  const [statusFilter, setStatusFilter] = useState("all");

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const data = await fetchMyLocationDocuments();
        if (cancelled) return;
        setLocationName(data?.location_name ?? null);
        setDocuments(Array.isArray(data?.documents) ? data.documents : []);
      } catch (e) {
        if (!cancelled) {
          setError(
            getApiErrorMessage(e, "Could not load SWIs for your location.")
          );
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  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 location 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">SWIs at my location</h1>
          <p className="portal-page-subtitle">
            {locationName
              ? `${summary.total} SWI document${summary.total === 1 ? "" : "s"} registered at ${locationName}.`
              : "Your profile has no plant assigned, or there are no SWIs at your location yet."}
          </p>
        </div>
      </header>

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

      {locationName ? (
        <section
          className="swi-user-stat-grid swi-user-stat-grid--compact"
          aria-label="Location SWI counts"
        >
          <UserStatCard
            label="Total at location"
            value={summary.total}
            hint={locationName}
            tone="opened"
          />
          <UserStatCard label="Opened" value={summary.counts[1] ?? 0} tone="opened" />
          <UserStatCard
            label="Assigned"
            value={summary.counts[2] ?? 0}
            tone="assigned"
          />
          <UserStatCard
            label="In progress"
            value={summary.inProgress}
            tone="in-progress"
          />
          <UserStatCard
            label="Completed"
            value={summary.completed}
            tone="completed"
          />
        </section>
      ) : null}

      <section className="swi-panel">
        {locationName ? (
          <UserSwiStatusFilter
            series={statusSeries}
            activeStatusId={statusFilter}
            onSelect={setStatusFilter}
          />
        ) : null}

        <UserSwiDocumentList
          documents={filtered}
          currentUserId={authUserId(auth)}
          onOpenForm={onOpenForm}
          onViewSubmission={onViewSubmission}
          showAssignee
          emptyMessage={
            locationName
              ? statusFilter === "all"
                ? "No SWI documents at your location yet."
                : "No SWIs in this status at your location."
              : "Set your plant in the user profile to see location SWIs."
          }
        />
      </section>
    </div>
  );
}
