'use client';

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 { MetricCard } from '@/components/dashboard/metric-card';
import { TaskFeed } from '@/components/dashboard/task-feed';
import { StatusPill } from '@/components/ui/status-pill';
import { useAuthGuard } from '@/hooks/use-auth-guard';
import { useTaskPoller } from '@/hooks/use-task-poller';
import {
  getLatestPortfolioInsight,
  getPortfolioSummary,
  getTask,
  listFilings,
  listRecentTasks,
  listWatchlist,
  queuePortfolioInsights,
  queuePriceRefresh
} from '@/lib/api';
import type { PortfolioInsight, PortfolioSummary, Task } from '@/lib/types';
import { formatCompactCurrency, formatCurrency, formatPercent } from '@/lib/format';

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 [state, setState] = useState<DashboardState>(EMPTY_STATE);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTaskId, setActiveTaskId] = useState<string | null>(null);

  const loadData = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      const [summaryRes, filingsRes, watchlistRes, tasksRes, insightRes] = await Promise.all([
        getPortfolioSummary(),
        listFilings({ limit: 200 }),
        listWatchlist(),
        listRecentTasks(20),
        getLatestPortfolioInsight()
      ]);

      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);
    }
  }, []);

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

  const trackedTask = useTaskPoller({
    taskId: activeTaskId,
    onTerminalState: () => {
      setActiveTaskId(null);
      void loadData();
    }
  });

  const headerActions = (
    <>
      <Button
        variant="secondary"
        onClick={async () => {
          try {
            const { task } = await queuePriceRefresh();
            setActiveTaskId(task.id);
            const latest = await getTask(task.id);
            setState((prev) => ({ ...prev, tasks: [latest.task, ...prev.tasks] }));
          } catch (err) {
            setError(err instanceof Error ? err.message : 'Failed to queue price refresh');
          }
        }}
      >
        <RefreshCw className="size-4" />
        Refresh prices
      </Button>
      <Button
        onClick={async () => {
          try {
            const { task } = await queuePortfolioInsights();
            setActiveTaskId(task.id);
            const latest = await getTask(task.id);
            setState((prev) => ({ ...prev, tasks: [latest.task, ...prev.tasks] }));
          } catch (err) {
            setError(err instanceof Error ? err.message : 'Failed to queue AI insight');
          }
        }}
      >
        <Sparkles className="size-4" />
        Queue AI insight
      </Button>
    </>
  );

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

  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={`Welcome back${session?.user?.name ? `, ${session.user.name}` : ''}. Review tasks, portfolio health, and AI outputs.`}
      actions={headerActions}
    >
      {activeTaskId && trackedTask ? (
        <Panel title="Live Task" subtitle={`Task ${activeTaskId.slice(0, 8)} is active.`}>
          <div className="flex items-center justify-between gap-3 rounded-lg border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-3 py-2">
            <p className="text-sm text-[color:var(--terminal-bright)]">{trackedTask.task_type.replace('_', ' ')}</p>
            <StatusPill status={trackedTask.status} />
          </div>
          {trackedTask.error ? (
            <p className="mt-3 text-sm text-[#ff9898]">{trackedTask.error}</p>
          ) : null}
        </Panel>
      ) : null}

      {error ? (
        <Panel>
          <p className="text-sm text-[#ffb5b5]">{error}</p>
        </Panel>
      ) : null}

      <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
        <MetricCard label="Portfolio Value" value={formatCurrency(state.summary.total_value)} delta={formatCompactCurrency(state.summary.total_cost_basis)} />
        <MetricCard
          label="Unrealized P&L"
          value={signedGain}
          delta={formatPercent(state.summary.avg_return_pct)}
          positive={Number(state.summary.total_gain_loss) >= 0}
        />
        <MetricCard label="Tracked Filings" value={String(state.filingsCount)} delta="Last 200 records" />
        <MetricCard label="Watchlist Nodes" value={String(state.watchlistCount)} delta={`${state.summary.positions} positions active`} />
      </div>

      <div className="grid grid-cols-1 gap-6 xl:grid-cols-3">
        <Panel title="Recent Tasks" subtitle="Durable jobs from queue processor" className="xl:col-span-1">
          {loading ? (
            <p className="text-sm text-[color:var(--terminal-muted)]">Loading tasks...</p>
          ) : (
            <TaskFeed tasks={state.tasks} />
          )}
        </Panel>

        <Panel title="AI Brief" subtitle="Latest portfolio insight from OpenClaw/ZeroClaw" className="xl:col-span-2">
          {loading ? (
            <p className="text-sm text-[color:var(--terminal-muted)]">Loading intelligence output...</p>
          ) : state.latestInsight ? (
            <>
              <div className="mb-3 inline-flex items-center gap-2 rounded-md border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-2 py-1 text-xs text-[color:var(--terminal-muted)]">
                <Bot className="size-3.5" />
                {state.latestInsight.provider} :: {state.latestInsight.model}
              </div>
              <p className="whitespace-pre-wrap text-sm leading-6 text-[color:var(--terminal-bright)]">{state.latestInsight.content}</p>
            </>
          ) : (
            <p className="text-sm text-[color:var(--terminal-muted)]">No AI brief yet. Queue one from the action bar.</p>
          )}
        </Panel>
      </div>

      <Panel title="Quick Links" subtitle="Feature modules">
        <div className="grid grid-cols-1 gap-3 md:grid-cols-3">
          <Link className="rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-4 transition hover:border-[color:var(--line-strong)] hover:bg-[color:var(--panel-bright)]" href="/filings">
            <p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Filings</p>
            <p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Sync SEC filings and trigger AI memo analysis.</p>
          </Link>
          <Link className="rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-4 transition hover:border-[color:var(--line-strong)] hover:bg-[color:var(--panel-bright)]" href="/portfolio">
            <p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Portfolio</p>
            <p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Manage holdings and mark to market in real time.</p>
          </Link>
          <Link className="rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-4 transition hover:border-[color:var(--line-strong)] hover:bg-[color:var(--panel-bright)]" href="/watchlist">
            <p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Watchlist</p>
            <p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Track priority tickers for monitoring and ingestion.</p>
          </Link>
        </div>
      </Panel>

      <Panel>
        <div className="flex items-center gap-2 text-xs uppercase tracking-[0.24em] text-[color:var(--terminal-muted)]">
          <Activity className="size-4" />
          Runtime state: {loading ? 'syncing' : 'stable'}
        </div>
      </Panel>
    </AppShell>
  );
}
