import React, { useEffect, useMemo, useState } from "react";
import LocationSwisChart from "../../components/user/charts/LocationSwisChart.jsx";
import UserAssignmentTrendChart from "../../components/user/charts/UserAssignmentTrendChart.jsx";
import UserSwiStatusChart from "../../components/user/charts/UserSwiStatusChart.jsx";
import RecentUndoneSwisList from "../../components/user/RecentUndoneSwisList.jsx";
import RemainingSwisPanel from "../../components/user/RemainingSwisPanel.jsx";
import SwiPersonalDashboardCatalog from "../../components/user/personalized/SwiPersonalDashboardCatalog.jsx";
import AddToPersonalizedButton from "../../components/user/personalized/AddToPersonalizedButton.jsx";
import UserStatCard from "../../components/user/UserStatCard.jsx";
import { SWI_DOCUMENT_STATUS } from "../../constants/swiDocumentStatus.js";
import { useAuth } from "../../context/AuthContext.jsx";
import {
  fetchMyAssignments,
  fetchMyLocationDocuments,
  fetchMyProfile,
} from "../../services/swiApi.js";
import { getApiErrorMessage } from "../../utils/apiError.js";
import { userSwiSummary } from "../../utils/userSwiStats.js";

function QuickLink({ label, desc, onClick }) {
  return (
    <button type="button" className="swi-user-quick-link" onClick={onClick}>
      <span className="swi-user-quick-link__label">{label}</span>
      <span className="swi-user-quick-link__desc">{desc}</span>
    </button>
  );
}

export default function UserHomePage({ onNavigate, onOpenForm, onViewSubmission }) {
  const { auth } = useAuth();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [profile, setProfile] = useState(null);
  const [assignments, setAssignments] = useState([]);
  const [locationData, setLocationData] = useState({
    location_name: null,
    documents: [],
  });

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [me, mine, atLocation] = await Promise.all([
          fetchMyProfile(),
          fetchMyAssignments(),
          fetchMyLocationDocuments(),
        ]);
        if (cancelled) return;
        setProfile(me);
        setAssignments(Array.isArray(mine) ? mine : []);
        setLocationData(
          atLocation && typeof atLocation === "object"
            ? {
                location_name: atLocation.location_name ?? null,
                documents: Array.isArray(atLocation.documents)
                  ? atLocation.documents
                  : [],
              }
            : { location_name: null, documents: [] }
        );
      } catch (e) {
        if (!cancelled) {
          setError(getApiErrorMessage(e, "Could not load your dashboard."));
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const mySummary = useMemo(() => userSwiSummary(assignments), [assignments]);
  const locationSummary = useMemo(
    () => userSwiSummary(locationData.documents),
    [locationData.documents]
  );

  const locationChartDocuments = useMemo(() => {
    const merged = new Map();
    for (const doc of locationData.documents) {
      merged.set(`${doc.document_id}-${doc.document_number}`, doc);
    }
    for (const doc of assignments) {
      if (doc.location_name) {
        merged.set(`${doc.document_id}-${doc.document_number}`, doc);
      }
    }
    return Array.from(merged.values());
  }, [locationData.documents, assignments]);

  const displayName =
    profile?.employee_name ||
    auth?.user?.employee_name ||
    auth?.user?.email_id ||
    "there";

  const goLocationSwis = () => onNavigate?.("my-location-swis");
  const goMySwis = () => onNavigate?.("my-swis");
  const goAssignedSwis = () => onNavigate?.("assigned-swis");

  const handleStatusBarClick = (item) => {
    if (item.statusId === SWI_DOCUMENT_STATUS.ASSIGNED) {
      onNavigate?.("assigned-swis", { filter: "awaiting" });
      return;
    }
    if (item.statusId === SWI_DOCUMENT_STATUS.IN_PROGRESS) {
      onNavigate?.("assigned-swis", { filter: "in-progress" });
      return;
    }
    onNavigate?.("my-swis", { statusFilter: item.statusId ?? "all" });
  };

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

  return (
    <div className="swi-user-home">
      <header className="portal-page-header portal-page-header--solo">
        <div className="portal-page-header__text">
          <h1 className="portal-page-title">Welcome, {displayName}</h1>
          <p className="portal-page-subtitle">
            {profile?.location_name
              ? `Your plant: ${profile.location_name}. Charts and tasks for your assigned SWIs.`
              : "Charts and tasks for your assigned SWIs."}
          </p>
        </div>
      </header>

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

      <section className="swi-user-stat-section">
        <div className="swi-user-stat-section__head">
          <h2 className="swi-user-section-title">Summary</h2>
          <AddToPersonalizedButton
            widgetId="swiStatsSummary"
            label="Add stats"
            className="swi-add-to-pd--compact"
          />
        </div>
        <div
          className="swi-user-stat-grid"
          aria-label="Your SWI summary"
        >
        <UserStatCard
          label="My SWIs"
          value={mySummary.total}
          hint="Assigned to you"
          tone="assigned"
          onClick={goMySwis}
        />
        <UserStatCard
          label="Incomplete SWIs"
          value={mySummary.pending}
          hint="SWIs assigned to you that are not yet completed"
          tone="in-progress"
          onClick={goAssignedSwis}
        />
        <UserStatCard
          label="Completed SWIs"
          value={mySummary.completed}
          hint="SWIs assigned to you that are completed"
          tone="completed"
          onClick={() =>
            onNavigate?.("my-swis", {
              statusFilter: SWI_DOCUMENT_STATUS.COMPLETED,
            })
          }
        />
        <UserStatCard
          label="At my location"
          value={locationSummary.total}
          hint={
            locationData.location_name
              ? `All SWIs at ${locationData.location_name}`
              : "All SWIs at your plant"
          }
          tone="opened"
          onClick={goLocationSwis}
        />
        </div>
      </section>
      <RemainingSwisPanel
          assignments={assignments}
          onViewRemaining={() => onNavigate?.("assigned-swis")}
        />

      <div className="swi-user-dashboard-charts">
        {/* <LocationSwisChart
          documents={locationChartDocuments}
          locationName={locationData.location_name || profile?.location_name}
          loading={loading}
          onClick={goLocationSwis}
          onBarClick={goLocationSwis}
        /> */}
        <UserSwiStatusChart
          assignments={assignments}
          userName={displayName}
          loading={loading}
          onClick={goMySwis}
          onBarClick={handleStatusBarClick}
        />
      </div>

      <UserAssignmentTrendChart
        assignments={assignments}
        loading={loading}
        onClick={goAssignedSwis}
        onBarClick={goAssignedSwis}
      />



      <SwiPersonalDashboardCatalog />

      <div className="swi-user-dashboard-panels">

        <RecentUndoneSwisList
          assignments={assignments}
          onOpenForm={onOpenForm}
          onViewAll={() => onNavigate?.("assigned-swis")}
        />
      </div>
      <section className="swi-panel swi-user-home__quick">
        <h2 className="swi-user-section-title">Quick access</h2>
        <div className="swi-user-quick-grid">
          <QuickLink
            label="Assigned SWIs"
            desc="New admin assignments and your task queue"
            onClick={() => onNavigate?.("assigned-swis")}
          />
          <QuickLink
            label="My SWIs"
            desc="All documents assigned to you"
            onClick={() => onNavigate?.("my-swis")}
          />
          <QuickLink
            label="SWIs at my location"
            desc="Every document registered at your plant"
            onClick={() => onNavigate?.("my-location-swis")}
          />
          <QuickLink
            label="Assignment list"
            desc="List or card view with start-work actions"
            onClick={() => onNavigate?.("assignment-list")}
          />
        </div>
      </section>
    </div>
  );
}
