import { useEffect, useMemo, useState, lazy, Suspense, type ReactNode } from "react";
import { ChevronDown } from "lucide-react";
import { Link } from "@tanstack/react-router";
import { Card } from "@/components/ui/card";
import { FocusMixPie } from "@/components/log/FocusMixPie";
import { LogHero } from "@/components/log/LogHero";
import { PrimeTime } from "@/components/log/PrimeTime";
import { RangePicker } from "@/components/log/RangePicker";
import { SessionsList } from "@/components/log/SessionsList";

// Heavy surfaces (charts, calendar grid, notes timeline) load on demand so the
// Activity screen opens instantly instead of waiting on the charting library.
const FocusTrendChart = lazy(() =>
  import("@/components/log/FocusTrendChart").then((m) => ({ default: m.FocusTrendChart })),
);
const FocusCalendar = lazy(() =>
  import("@/components/FocusCalendar").then((m) => ({ default: m.FocusCalendar })),
);
const ReflectionsTimeline = lazy(() =>
  import("@/components/log/ReflectionsTimeline").then((m) => ({ default: m.ReflectionsTimeline })),
);

const cardFallback = (
  <div className="h-40 rounded-xl bg-muted/30 animate-pulse" />
);
import { rangeLabel } from "@/lib/logRange";
import { deriveInsights } from "@/lib/logInsights";
import { useAuth } from "@/hooks/useAuth";
import { cn } from "@/lib/utils";
import type { Session } from "@/lib/storage";
import {
  filterByRange,
  loadRange,
  type LogRange,
} from "@/lib/logRange";

export function Stats({
  sessions,
  onDeleteSession,
  onAskAum,
}: {
  sessions: Session[];
  onDeleteSession?: (session: Session) => Promise<void> | void;
  onAskAum?: () => void;
}) {
  const { user } = useAuth();
  const [range, setRange] = useState<LogRange>({ kind: "7d" });
  const [view, setView] = useState<"stats" | "calendar" | "notes">("stats");
  // Editorial default: everything collapsed on each visit. No persistence.
  const [openSections, setOpenSections] = useState<Record<string, boolean>>({
    trend: false,
    mix: false,
    prime: false,
    sessions: false,
  });
  const toggleSection = (id: string) =>
    setOpenSections((s) => {
      const next = { ...s, [id]: !s[id] };
      // Smoothly scroll the just-expanded card into view.
      if (!s[id]) {
        requestAnimationFrame(() => {
          const el = document.getElementById(`card-${id}`);
          el?.scrollIntoView({ behavior: "smooth", block: "start" });
        });
      }
      return next;

    });

  useEffect(() => {
    setRange(loadRange());
  }, []);

  const updateRange = (r: LogRange) => {
    setRange(r);
  };

  const rangeSessions = useMemo(() => filterByRange(sessions, range), [sessions, range]);
  const insights = useMemo(
    () => deriveInsights(rangeSessions, sessions, range),
    [rangeSessions, sessions, range],
  );

  if (sessions.length === 0) {
    return (
      <div className="space-y-4">
        {!user && (
          <p className="text-xs text-muted-foreground text-center">
            <Link
              to="/login"
              search={{ redirect: "/" }}
              className="underline decoration-dotted underline-offset-4 hover:text-foreground"
            >
              Sign in
            </Link>{" "}
            to save your activity across devices.
          </p>
        )}
        <Card className="p-8 text-center text-muted-foreground space-y-2">
          <p className="text-foreground font-medium">Your activity is empty</p>
          <p className="text-sm">
            Start your first session — even 10 minutes counts.
          </p>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Full-bleed backdrop, but the controls stay inside the page column so
          they line up with every card below at any width. */}
      <div className="sticky top-0 z-20 w-screen max-w-[100vw] ml-[calc(50%-50vw)] py-2 sm:py-3 bg-background/70 backdrop-blur-md border-b border-border/40">
        <div className="mx-auto w-full max-w-3xl px-4 sm:px-8 md:px-10 lg:px-8">
          <RangePicker value={range} onChange={updateRange} view={view} onViewChange={setView} />
        </div>
      </div>

      {view === "calendar" ? (
        <Card className="p-5">
          <Suspense fallback={cardFallback}>
            <FocusCalendar sessions={sessions} year="rolling" hideHeader />
          </Suspense>
        </Card>
      ) : view === "notes" ? (
        <Suspense fallback={cardFallback}>
          <ReflectionsTimeline sessions={sessions} onAskAum={onAskAum} />
        </Suspense>
      ) : (
        <>
          <LogHero
            range={range}
            rangeSessions={rangeSessions}
            allSessions={sessions}
          />

          {rangeSessions.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-4">
              No sessions in this range — try a wider window.
            </p>
          ) : (
            <div data-tour="stats" className="space-y-8">
              <CollapsibleCard
                id="trend"
                eyebrow="Focus trend"
                insight={insights.trend}
                open={openSections.trend}
                onToggle={toggleSection}
              >
                <Suspense fallback={cardFallback}>
                  <FocusTrendChart
                    rangeSessions={rangeSessions}
                    range={range}
                    allSessions={sessions}
                  />
                </Suspense>
              </CollapsibleCard>

              <CollapsibleCard
                id="mix"
                eyebrow="Focus mix"
                insight={insights.mix}
                open={openSections.mix}
                onToggle={toggleSection}
              >
                <FocusMixPie rangeSessions={rangeSessions} range={range} />
              </CollapsibleCard>

              <CollapsibleCard
                id="prime"
                eyebrow="Prime time"
                insight={insights.prime}
                open={openSections.prime}
                onToggle={toggleSection}
              >
                <PrimeTime
                  sessions={sessions}
                  rangeSessions={rangeSessions}
                  rangeLabel={rangeLabel(range, sessions)}
                  range={range}
                />
              </CollapsibleCard>

              <CollapsibleCard
                id="sessions"
                eyebrow="Sessions"
                insight={insights.sessions}
                open={openSections.sessions}
                onToggle={toggleSection}
              >
                <SessionsList
                  rangeSessions={rangeSessions}
                  range={range}
                  allSessions={sessions}
                  onDelete={onDeleteSession}
                />
              </CollapsibleCard>

            </div>
          )}
        </>
      )}
    </div>
  );
}

function CollapsibleCard({
  id,
  eyebrow,
  insight,
  open,
  onToggle,
  children,
}: {
  id: string;
  eyebrow: string;
  insight: string;
  open: boolean;
  onToggle: (id: string) => void;
  children: ReactNode;
}) {
  const panelId = `collapsible-${id}`;
  return (
    <Card id={`card-${id}`} className="p-5 sm:p-6 scroll-mt-24">
      <button
        type="button"
        onClick={() => onToggle(id)}
        aria-expanded={open}
        aria-controls={panelId}
        className="w-full flex items-start justify-between gap-4 text-left group"
      >
        <div className="min-w-0 space-y-1.5">
          <div className="text-[10px] uppercase tracking-[0.18em] text-muted-foreground/80">
            {eyebrow}
          </div>
          <p
            className={cn(
              "text-[15px] sm:text-base leading-snug text-foreground/90",
              open && "text-muted-foreground text-sm",
            )}
          >
            {insight}
          </p>
        </div>
        <ChevronDown
          className={cn(
            "size-4 shrink-0 mt-1 text-muted-foreground transition-transform duration-200 group-hover:text-foreground",
            open ? "" : "-rotate-90",
          )}
        />
      </button>
      {open && (
        <div id={panelId} className="mt-5">
          {children}
        </div>
      )}
    </Card>
  );
}
