"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "convex/react";
import { api } from "../../../convex/_generated/api";
import type { CommandCenterData, CCRange } from "@/lib/queries/command-center";
import { Hero } from "./hero";
import { KpiStrip } from "./kpi-strip";
import { FlagshipChart } from "./flagship-chart";
import { LiveOps } from "./live-ops";
import { Portfolio } from "./portfolio";
import { Forecast } from "./forecast";
import { WorkersPanel } from "./workers-panel";
import { ActivityStream } from "./activity-stream";
import { AttentionCenter } from "./attention";
import { Opportunities } from "./opportunities";
import { Insights } from "./insights";
import { SourceMix } from "./source-mix";
import { MobileCommandCenter } from "./mobile";
import { Reveal } from "@/components/motion/reveal";

export interface CCProps {
  initial: CommandCenterData;
  user: { firstName: string; showProfit: boolean; canBlock: boolean; canCreate: boolean };
  currency: string;
  timezone: string;
  initialRange: CCRange;
  initialCustom?: { from?: string; to?: string };
}

export type { CommandCenterData, CCRange };

/**
 * Live business command center. The server renders the first payload; the
 * client then subscribes to the same Convex query, so every KPI, operation
 * and activity row updates the moment any mutation commits — no polling.
 */
export function CommandCenter({ initial, user, currency, timezone, initialRange, initialCustom }: CCProps) {
  const router = useRouter();
  const [range, setRange] = React.useState<CCRange>(initialRange);
  const [custom, setCustom] = React.useState<{ from?: string; to?: string }>(initialCustom ?? {});
  const live = useQuery(api.dashboard.commandCenter, { range, from: custom.from, to: custom.to }) as CommandCenterData | undefined;
  const data = live ?? initial;
  const loading = live === undefined && (range !== initialRange || custom.from !== initialCustom?.from || custom.to !== initialCustom?.to);
  const [updatedAt, setUpdatedAt] = React.useState<Date>(new Date(initial.generatedAt));
  React.useEffect(() => {
    if (live) setUpdatedAt(new Date());
  }, [live]);

  const changeRange = (r: CCRange, c?: { from?: string; to?: string }) => {
    setRange(r);
    if (c) setCustom(c);
    const sp = new URLSearchParams({ range: r });
    if (c?.from) sp.set("from", c.from);
    if (c?.to) sp.set("to", c.to);
    window.history.replaceState(null, "", `/dashboard?${sp.toString()}`);
  };

  const refresh = () => {
    setUpdatedAt(new Date());
    router.refresh();
  };

  return (
    <>
    <MobileCommandCenter data={data} range={range} onRange={(r) => changeRange(r)} loading={loading} updatedAt={updatedAt} onRefresh={refresh} firstName={user.firstName} currency={currency} showProfit={user.showProfit} />
    <div className="hidden space-y-5 md:block">
      <Hero data={data} range={range} custom={custom} onRange={changeRange} loading={loading} updatedAt={updatedAt} onRefresh={refresh} firstName={user.firstName} currency={currency} timezone={timezone} canCreate={user.canCreate} canBlock={user.canBlock} />
      <KpiStrip hero={data.hero} recovery={data.recovery} trend={data.trend} currency={currency} showProfit={user.showProfit} />
      <Reveal className="grid gap-4 xl:grid-cols-3">
        <FlagshipChart trend={data.trend} period={data.period} hero={data.hero} ops={data.ops} forecast={data.forecast} bySource={data.bySource} currency={currency} showProfit={user.showProfit} className="xl:col-span-2" loading={loading} />
        <div className="grid min-w-0 content-start gap-4">
          <AttentionCenter items={data.attention} />
          <Opportunities items={data.opportunities} recovery={data.recovery} currency={currency} />
        </div>
      </Reveal>
      <Reveal>
        <LiveOps ops={data.ops} today={data.period.today} currency={currency} />
      </Reveal>
      <Reveal className="grid gap-4 xl:grid-cols-3">
        <Portfolio items={data.portfolio} counts={data.statusCounts} currency={currency} className="xl:col-span-2" />
        <Forecast forecast={data.forecast} heatmap={data.heatmap} />
      </Reveal>
      <Reveal className="grid gap-4 xl:grid-cols-3">
        <WorkersPanel workers={data.workers} currency={currency} className="xl:col-span-2" />
        <ActivityStream items={data.activity} />
      </Reveal>
      <Reveal className="grid gap-4 lg:grid-cols-2">
        <Insights items={data.insights} period={data.period.label} />
        <SourceMix bySource={data.bySource} expenses={data.expensesByCategory} currency={currency} />
      </Reveal>
    </div>
    </>
  );
}
