"use client";

import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Activity, Bot, RefreshCw, Sparkles } from "lucide-react";
import { AppShell } from "@/components/shell/app-shell";
import { Panel } from "@/components/ui/panel";
import { Button } from "@/components/ui/button";
import { TaskFeed } from "@/components/dashboard/task-feed";
import { IndexCardRow } from "@/components/dashboard/index-card-row";
import { useAuthGuard } from "@/hooks/use-auth-guard";
import { useLinkPrefetch } from "@/hooks/use-link-prefetch";
import { queuePortfolioInsights, queuePriceRefresh } from "@/lib/api";
import { buildGraphingHref } from "@/lib/graphing/catalog";
import type { PortfolioInsight, PortfolioSummary, Task } from "@/lib/types";
import {
  formatCompactCurrency,
  formatCurrency,
  formatPercent,
} from "@/lib/format";
import { queryKeys } from "@/lib/query/keys";
import {
  filingsQueryOptions,
  latestPortfolioInsightQueryOptions,
  portfolioSummaryQueryOptions,
  recentTasksQueryOptions,
  watchlistQueryOptions,
} from "@/lib/query/options";

type DashboardState = {
  summary: PortfolioSummary;
  filingsCount: number;
  watchlistCount: number;
  tasks: Task[];
  latestInsight: PortfolioInsight | null;
};

const EMPTY_STATE: DashboardState = {
  summary: {
    positions: 0,
    total_value: "0",
    total_gain_loss: "0",
    total_cost_basis: "0",
    avg_return_pct: "0",
  },
  filingsCount: 0,
  watchlistCount: 0,
  tasks: [],
  latestInsight: null,
};

export default function CommandCenterPage() {
  const { isPending, isAuthenticated, session } = useAuthGuard();
  const queryClient = useQueryClient();
  const { prefetchPortfolioSurfaces } = useLinkPrefetch();
  const [state, setState] = useState<DashboardState>(EMPTY_STATE);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadData = useCallback(async () => {
    const summaryOptions = portfolioSummaryQueryOptions();
    const filingsOptions = filingsQueryOptions({ limit: 200 });
    const watchlistOptions = watchlistQueryOptions();
    const tasksOptions = recentTasksQueryOptions(20);
    const insightOptions = latestPortfolioInsightQueryOptions();

    if (!queryClient.getQueryData(summaryOptions.queryKey)) {
      setLoading(true);
    }

    setError(null);

    try {
      const [summaryRes, filingsRes, watchlistRes, tasksRes, insightRes] =
        await Promise.all([
          queryClient.ensureQueryData(summaryOptions),
          queryClient.ensureQueryData(filingsOptions),
          queryClient.ensureQueryData(watchlistOptions),
          queryClient.ensureQueryData(tasksOptions),
          queryClient.ensureQueryData(insightOptions),
        ]);

      setState({
        summary: summaryRes.summary,
        filingsCount: filingsRes.filings.length,
        watchlistCount: watchlistRes.items.length,
        tasks: tasksRes.tasks,
        latestInsight: insightRes.insight,
      });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load dashboard");
    } finally {
      setLoading(false);
    }
  }, [queryClient]);

  useEffect(() => {
    if (!isPending && isAuthenticated) {
      void loadData();
    }
  }, [isPending, isAuthenticated, loadData]);

  const headerActions = (
    <div className="flex gap-2">
      <Button
        variant="secondary"
        size="compact"
        onClick={async () => {
          try {
            await queuePriceRefresh();
            void queryClient.invalidateQueries({
              queryKey: queryKeys.recentTasks(20),
            });
            void queryClient.invalidateQueries({
              queryKey: queryKeys.portfolioSummary(),
            });
            await loadData();
          } catch (err) {
            setError(
              err instanceof Error
                ? err.message
                : "Failed to queue price refresh",
            );
          }
        }}
      >
        <RefreshCw className="size-3.5" />
        Refresh
      </Button>
      <Button
        size="compact"
        onClick={async () => {
          try {
            await queuePortfolioInsights();
            void queryClient.invalidateQueries({
              queryKey: queryKeys.recentTasks(20),
            });
            void queryClient.invalidateQueries({
              queryKey: queryKeys.latestPortfolioInsight(),
            });
            await loadData();
          } catch (err) {
            setError(
              err instanceof Error ? err.message : "Failed to queue AI insight",
            );
          }
        }}
      >
        <Sparkles className="size-3.5" />
        AI Insight
      </Button>
    </div>
  );

  const signedGain = useMemo(() => {
    const gain = Number(state.summary.total_gain_loss ?? 0);
    return gain >= 0 ? `+${formatCurrency(gain)}` : formatCurrency(gain);
  }, [state.summary.total_gain_loss]);

  const indexCards = useMemo(
    () => [
      {
        label: "Portfolio Value",
        value: formatCurrency(state.summary.total_value),
        delta: formatCompactCurrency(state.summary.total_cost_basis),
      },
      {
        label: "Unrealized P&L",
        value: signedGain,
        delta: formatPercent(state.summary.avg_return_pct),
        positive: Number(state.summary.total_gain_loss) >= 0,
      },
      {
        label: "Filings",
        value: String(state.filingsCount),
        delta: "Last 200",
      },
      {
        label: "Coverage",
        value: String(state.watchlistCount),
        delta: `${state.summary.positions} active`,
      },
    ],
    [state, signedGain],
  );

  if (isPending || !isAuthenticated) {
    return (
      <div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">
        Booting secure terminal...
      </div>
    );
  }

  return (
    <AppShell
      title="Command Center"
      subtitle={
        session?.user?.name
          ? `Welcome back, ${session.user.name}`
          : "Review tasks, portfolio health, and AI outputs."
      }
      actions={headerActions}
    >
      {error ? (
        <div className="rounded-lg border border-[color:var(--line-weak)] bg-[color:var(--danger-soft)] px-3 py-2 text-sm text-[#ffb5b5]">
          {error}
        </div>
      ) : null}

      <div className="rounded-lg border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)]">
        <IndexCardRow cards={indexCards} />
      </div>

      <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
        <div className="border-t border-[color:var(--line-weak)] pt-4 xl:col-span-1">
          <div className="mb-3 flex items-center justify-between">
            <h3 className="text-sm font-semibold text-[color:var(--terminal-bright)]">
              Recent Tasks
            </h3>
            <span className="terminal-caption text-[10px] uppercase tracking-[0.12em] text-[color:var(--terminal-muted)]">
              Queue Processor
            </span>
          </div>
          {loading ? (
            <p className="text-xs text-[color:var(--terminal-muted)]">
              Loading...
            </p>
          ) : (
            <TaskFeed tasks={state.tasks} />
          )}
        </div>

        <div className="border-t border-[color:var(--line-weak)] pt-4 xl:col-span-2">
          <div className="mb-3 flex items-center justify-between">
            <h3 className="text-sm font-semibold text-[color:var(--terminal-bright)]">
              AI Brief
            </h3>
            {state.latestInsight ? (
              <div className="inline-flex items-center gap-1.5 rounded border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-2 py-0.5 text-[10px] text-[color:var(--terminal-muted)]">
                <Bot className="size-3" />
                {state.latestInsight.provider} :: {state.latestInsight.model}
              </div>
            ) : null}
          </div>
          {loading ? (
            <p className="text-xs text-[color:var(--terminal-muted)]">
              Loading...
            </p>
          ) : state.latestInsight ? (
            <p className="whitespace-pre-wrap text-sm leading-6 text-[color:var(--terminal-bright)]">
              {state.latestInsight.content}
            </p>
          ) : (
            <p className="text-xs text-[color:var(--terminal-muted)]">
              No AI brief yet. Queue one from the action bar.
            </p>
          )}
        </div>
      </div>

      <div className="border-t border-[color:var(--line-weak)] pt-4">
        <h3 className="mb-3 text-sm font-semibold text-[color:var(--terminal-bright)]">
          Quick Links
        </h3>
        <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
          <Link
            className="border-l-2 border-[color:var(--line-weak)] py-1 pl-3 pr-2 transition hover:border-[color:var(--line-strong)]"
            href="/analysis"
          >
            <p className="panel-heading text-[10px] uppercase tracking-[0.14em] text-[color:var(--terminal-muted)]">
              Overview
            </p>
            <p className="mt-1 text-xs text-[color:var(--terminal-bright)]">
              Company analysis, price, valuation, and developments.
            </p>
          </Link>
          <Link
            className="border-l-2 border-[color:var(--line-weak)] py-1 pl-3 pr-2 transition hover:border-[color:var(--line-strong)]"
            href="/financials"
          >
            <p className="panel-heading text-[10px] uppercase tracking-[0.14em] text-[color:var(--terminal-muted)]">
              Financials
            </p>
            <p className="mt-1 text-xs text-[color:var(--terminal-bright)]">
              Multi-period metrics, margins, and balance sheet.
            </p>
          </Link>
          <Link
            className="border-l-2 border-[color:var(--line-weak)] py-1 pl-3 pr-2 transition hover:border-[color:var(--line-strong)]"
            href={buildGraphingHref()}
          >
            <p className="panel-heading text-[10px] uppercase tracking-[0.14em] text-[color:var(--terminal-muted)]">
              Graphing
            </p>
            <p className="mt-1 text-xs text-[color:var(--terminal-bright)]">
              Compare normalized metrics across companies.
            </p>
          </Link>
          <Link
            className="border-l-2 border-[color:var(--line-weak)] py-1 pl-3 pr-2 transition hover:border-[color:var(--line-strong)]"
            href="/filings"
            onMouseEnter={() => {
              void queryClient.prefetchQuery(
                filingsQueryOptions({ limit: 120 }),
              );
            }}
            onFocus={() => {
              void queryClient.prefetchQuery(
                filingsQueryOptions({ limit: 120 }),
              );
            }}
          >
            <p className="panel-heading text-[10px] uppercase tracking-[0.14em] text-[color:var(--terminal-muted)]">
              Filings
            </p>
            <p className="mt-1 text-xs text-[color:var(--terminal-bright)]">
              SEC filings and AI memo analysis.
            </p>
          </Link>
          <Link
            className="border-l-2 border-[color:var(--line-weak)] py-1 pl-3 pr-2 transition hover:border-[color:var(--line-strong)]"
            href="/portfolio"
            onMouseEnter={() => prefetchPortfolioSurfaces()}
            onFocus={() => prefetchPortfolioSurfaces()}
          >
            <p className="panel-heading text-[10px] uppercase tracking-[0.14em] text-[color:var(--terminal-muted)]">
              Portfolio
            </p>
            <p className="mt-1 text-xs text-[color:var(--terminal-bright)]">
              Manage positions and mark to market.
            </p>
          </Link>
          <Link
            className="border-l-2 border-[color:var(--line-weak)] py-1 pl-3 pr-2 transition hover:border-[color:var(--line-strong)]"
            href="/watchlist"
            onMouseEnter={() => prefetchPortfolioSurfaces()}
            onFocus={() => prefetchPortfolioSurfaces()}
          >
            <p className="panel-heading text-[10px] uppercase tracking-[0.14em] text-[color:var(--terminal-muted)]">
              Coverage
            </p>
            <p className="mt-1 text-xs text-[color:var(--terminal-bright)]">
              Track research status and filing freshness.
            </p>
          </Link>
        </div>
      </div>

      <div className="flex items-center gap-2 text-[10px] uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">
        <Activity className="size-3" />
        Runtime: {loading ? "syncing" : "stable"}
      </div>
    </AppShell>
  );
}
