"use client";

import { Suspense, useMemo, useState } from "react";
import { RefreshCw, SlidersHorizontal } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { FilterCombobox } from "@/components/app/filters";
import { PageContent, PageHeader } from "@/components/app/page";
import { OnboardingTip } from "../onboarding/onboarding-tip";
import { SavedViewsBar } from "@/components/app/saved-views";
import { cn } from "@/lib/utils";
import ProtectedRoute from "../auth/protected-route";
import { useAuth } from "../auth/auth-context";
import AppShell from "../components/app-shell";
import { EmptyState, ErrorState, UnauthorizedState } from "../components/ui/page-states";
import { useOrderLookups } from "../purchase-orders/useOrderSearch";
import { QuickActionSheet } from "../worklist/quick-action-sheet";
import { FlowMap } from "../onboarding/flow-map";
import { GetStartedCard } from "../onboarding/get-started-ui";
import { useSampleActions } from "../onboarding/sample-data-card";
import { useOnboarding } from "../onboarding/useOnboarding";
import { openQuickOrder } from "../onboarding/useQuickOrderForm";
import { recommendedStart } from "../onboarding/useWelcomeFlow";
import { StartOptions } from "../onboarding/welcome-ui";
import { DashboardFootnote, earlyTiles, MyQueue, OrderFlow, Performance, ShipHorizon, StageCards, TeamWorkload, TodayStrip } from "./dashboard-sections";
import { relativeTime, shortDate, useDashboardFilters, useDashboardOverview, WORKLIST_TYPE_LABELS } from "./useDashboard";

// Kept as re-exports so existing imports from this file keep working.
export { relativeTime, shortDate, WORKLIST_TYPE_LABELS };

export function LiveDashboardPage() {
  return <ProtectedRoute><AppShell title="Dashboard">
    {/* useSearchParams (URL filters) needs a Suspense boundary. */}
    <Suspense fallback={<DashboardSkeleton />}><Dashboard /></Suspense>
  </AppShell></ProtectedRoute>;
}

function DashboardSkeleton() {
  return <PageContent>
    <div className="grid gap-2"><Skeleton className="h-8 w-48" /><Skeleton className="h-4 w-96 max-w-full" /></div>
    <TodayStrip tiles={[]} isLoading />
    <OrderFlow isLoading />
  </PageContent>;
}

// Everything on the page is empty: no inquiries, no orders, nothing open.
function isEmptyOrganization(overview) {
  if (!overview?.flow) return false;
  const cells = [...overview.flow.sourcing, ...overview.flow.orders];
  return cells.length > 0 && cells.every((cell) => !cell.count) && !(overview.queue?.summary.total > 0) && !(overview.shipHorizon?.total > 0);
}

// Active POs across the order rail (every derived stage counts).
function activeOrderCount(overview) {
  return (overview?.flow?.orders || []).reduce((sum, cell) => sum + (Number(cell.count) || 0), 0);
}

const hasSignal = (stage) => stage.metrics.some((metric) => (Array.isArray(metric.value) ? metric.value.length > 0 : Number(metric.value) > 0));

/**
 * Stage 0 (design S11): no inquiry or PO yet, real or sample. Instead of an empty dashboard, the same start choices
 * as the welcome screen plus the order-flow map.
 */
function StartHere({ onboarding }) {
  const { can } = useAuth();
  const sample = useSampleActions();
  const canManage = Boolean(onboarding?.me.canManage || onboarding?.me.isOwner);
  const allowed = { sample: canManage, running_order: can("purchase_orders.create") };
  const profile = onboarding?.profile;
  const recommendation = recommendedStart({ tracking: profile?.trackingMethods || [], band: profile?.runningOrdersBand || "" });
  const choose = (choice) => (choice === "sample" ? sample.load() : openQuickOrder("dashboard"));

  return <section aria-labelledby="start-here-title" className="grid gap-4">
    <div className="grid gap-1">
      <h2 id="start-here-title" className="text-lg font-semibold tracking-tight">Start here</h2>
      <p className="text-sm text-muted-foreground">{allowed.sample && allowed.running_order ? "Pick one. You can do both, and the sample never mixes into your real numbers." : "Your first order puts the whole house in motion."}</p>
    </div>
    <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_340px] lg:items-start">
      {allowed.sample || allowed.running_order
        ? <StartOptions recommendation={recommendation} allowed={allowed} pending={sample.isLoading ? "sample" : null} onChoose={choose} />
        : <Card className="py-0"><EmptyState title="Nothing on the board yet" detail="Orders and inquiries appear here as your team adds them. Ask your owner to put in the first running order." /></Card>}
      <FlowMap />
    </div>
  </section>;
}

function Dashboard() {
  const { can } = useAuth();
  const allowed = can("dashboard.view");
  const { filters, savedFilters, update } = useDashboardFilters();
  const dashboard = useDashboardOverview(filters, allowed);
  const { overview, scope } = dashboard;
  const lookups = useOrderLookups();
  const onboarding = useOnboarding({ enabled: allowed }).data;
  const [acting, setActing] = useState(null);
  const [filtersOpen, setFiltersOpen] = useState(false);

  const buyerOptions = useMemo(() => lookups.buyers.map((buyer) => ({ value: buyer.code, label: buyer.name })), [lookups.buyers]);
  const factoryOptions = useMemo(() => lookups.factories.map((factory) => ({ value: factory.code, label: factory.name })), [lookups.factories]);

  if (!allowed) {
    return <PageContent><UnauthorizedState title="The dashboard is not available for your role" permission="dashboard.view" /></PageContent>;
  }

  const loading = dashboard.isLoading;
  const horizon = filters.horizon || String(overview?.filters?.horizon || 30);
  const period = filters.period || overview?.filters?.period || "30d";
  const filterCount = [filters.buyer, filters.factory].filter(Boolean).length;
  const emptyOrg = !loading && !filters.buyer && !filters.factory && scope === "all" && isEmptyOrganization(overview);
  const sampleLoaded = onboarding?.sample.status === "loaded";
  // A brand-new house (stage 0, no sample) gets "Start here" instead of filters and empty sections.
  const fresh = onboarding ? onboarding.stage === 0 && !sampleLoaded : emptyOrg;
  // Early houses (fewer than 3 active POs): no walls of zeros, no charts before there is anything to judge.
  const early = !fresh && !sampleLoaded && !loading && activeOrderCount(overview) < 3;
  const noShipmentsYet = onboarding ? onboarding.stage < 4 : false;
  const owners = (overview?.team || []).filter((row) => row.owner).length;
  const tiles = early ? earlyTiles(overview?.tiles || []) : overview?.tiles || [];
  const stages = early ? (overview?.stages || []).filter(hasSignal) : overview?.stages || [];
  const applyView = (view) => update({ scope: "", buyer: "", factory: "", horizon: "", period: "", ...(view.filters || {}) });

  const scopeControl = <Tabs value={scope} onValueChange={(value) => update({ scope: value })} className="w-full md:w-auto">
    <TabsList aria-label="Scope" className="grid w-full grid-cols-2 md:inline-flex md:w-auto">
      <TabsTrigger value="mine" className="px-3">Mine</TabsTrigger>
      <TabsTrigger value="all" className="px-3">Organization</TabsTrigger>
    </TabsList>
  </Tabs>;
  const filterControls = <>
    <FilterCombobox label="Buyer" value={filters.buyer} onChange={(buyer) => update({ buyer })} options={buyerOptions} allLabel="All buyers" searchPlaceholder="Search buyers…" className="w-full md:w-auto" />
    <FilterCombobox label="Factory" value={filters.factory} onChange={(factory) => update({ factory })} options={factoryOptions} allLabel="All factories" searchPlaceholder="Search factories…" className="w-full md:w-auto" />
  </>;
  const refreshButton = <Tooltip>
    <TooltipTrigger asChild>
      <Button variant="outline" size="icon-sm" onClick={dashboard.refresh} disabled={dashboard.isRefreshing} aria-label="Refresh dashboard">{dashboard.isRefreshing ? <Spinner /> : <RefreshCw />}</Button>
    </TooltipTrigger>
    <TooltipContent>Refresh · updated {dashboard.generatedAt ? relativeTime(dashboard.generatedAt) : "now"}</TooltipContent>
  </Tooltip>;

  return <PageContent>
    <PageHeader
      title="Dashboard"
      description={fresh
        ? "Your house at a glance will appear here as orders come in."
        : <>Where every inquiry and order stands, what is late or at risk, and what ships next{dashboard.generatedAt ? ` · updated ${relativeTime(dashboard.generatedAt)}` : ""}.</>}
      actions={fresh ? null : <>
        <div className="hidden items-center gap-2 md:flex">{scopeControl}{filterControls}{refreshButton}</div>
        <div className="grid w-full gap-2 md:hidden">
          {scopeControl}
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" className="flex-1" onClick={() => setFiltersOpen(true)}><SlidersHorizontal /> Filters{filterCount > 0 && <Badge variant="secondary" className="ml-1 h-5 px-1.5">{filterCount}</Badge>}</Button>
            {refreshButton}
          </div>
        </div>
      </>}
    />

    <OnboardingTip id="dashboard.intro" when={!fresh} />

    {!fresh && <SavedViewsBar module="dashboard" noun="the dashboard" filters={savedFilters} onApply={applyView} applyDefault className="hidden md:flex" />}

    <Sheet open={filtersOpen} onOpenChange={setFiltersOpen}>
      <SheetContent side="bottom" className="max-h-[85vh] overflow-y-auto">
        <SheetHeader><SheetTitle>Dashboard filters</SheetTitle><SheetDescription>Narrow every section to one buyer or factory.</SheetDescription></SheetHeader>
        <div className="grid gap-3 px-4 pb-6">
          {filterControls}
          <SavedViewsBar module="dashboard" noun="the dashboard" filters={savedFilters} onApply={(view) => { applyView(view); setFiltersOpen(false); }} />
          {filterCount > 0 && <Button variant="ghost" size="sm" onClick={() => update({ buyer: "", factory: "" })}>Clear filters</Button>}
        </div>
      </SheetContent>
    </Sheet>

    {dashboard.error
      ? <Card className="py-0"><ErrorState error={dashboard.error} title="The dashboard could not load" onRetry={dashboard.refresh} /></Card>
      : <>
        {!fresh && <GetStartedCard />}

        {fresh
          ? <StartHere onboarding={onboarding} />
          : <div className={cn("grid gap-6 transition-opacity xl:grid-cols-3", dashboard.isRefreshing && "opacity-60")} aria-busy={loading || dashboard.isRefreshing}>
            <div className="order-1 xl:col-span-3"><TodayStrip tiles={tiles} isLoading={loading} /></div>
            <div className="order-3 md:order-2 xl:col-span-3"><OrderFlow flow={overview?.flow} canSeeMoney={overview?.canSeeMoney} isLoading={loading} /></div>
            <ShipHorizon
              className="order-4 md:order-3 xl:col-span-2"
              horizon={overview?.shipHorizon}
              days={horizon}
              onDaysChange={(value) => update({ horizon: value })}
              isLoading={loading}
              onRetry={dashboard.refresh}
            />
            <MyQueue
              className={cn("order-2 md:order-4", !loading && !overview?.shipHorizon && "xl:col-span-3")}
              queue={overview?.queue}
              scope={scope}
              isLoading={loading}
              onAct={setActing}
              onShowOrganization={() => update({ scope: "all" })}
            />
          </div>}

        {!loading && !fresh && <>
          <StageCards stages={stages} />
          <TeamWorkload team={scope === "all" && !(early && owners < 2) ? overview?.team : null} />
          {!noShipmentsYet && <Performance performance={overview?.performance} period={period} onPeriodChange={(value) => update({ period: value })} periodStart={overview?.filters?.periodStart} periodEnd={overview?.filters?.periodEnd} />}
        </>}

        {!fresh && <DashboardFootnote generatedAt={dashboard.generatedAt} />}
      </>}

    <QuickActionSheet item={acting} onClose={() => setActing(null)} />
  </PageContent>;
}
