"use client";

import { useEffect, useState } from "react";
import { DollarSign, TrendingUp, Activity, Bot } from "lucide-react";

import { MetricCard } from "@/components/ui/MetricCard";
import { AgentTable } from "@/components/agents/AgentTable";
import { TradeList } from "@/components/ui/TradeList";
import { EquityChart } from "@/components/ui/EquityChart";
import { PnlDistributionChart } from "@/components/ui/PnlDistributionChart";
import { getMetrics, getEquityCurve, getPnlDistribution } from "@/api/metrics";
import { getAgents } from "@/api/agents";
import { getRecentTrades } from "@/api/trades";
import type {
  AgentStatus,
  TradeRecord,
  Metrics,
  EquityPoint,
  PnlDistribution,
} from "@/types/models";

export default function Dashboard() {
  const [metrics, setMetrics] = useState<Metrics | null>(null);
  const [equityData, setEquityData] = useState<EquityPoint[]>([]);
  const [pnlDistribution, setPnlDistribution] = useState<PnlDistribution[]>([]);
  const [agents, setAgents] = useState<AgentStatus[]>([]);
  const [trades, setTrades] = useState<TradeRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchData() {
      try {
        setLoading(true);
        const [metricsRes, equityRes, pnlRes, agentsRes, tradesRes] =
          await Promise.all([
            getMetrics(),
            getEquityCurve(),
            getPnlDistribution(),
            getAgents(),
            getRecentTrades(10),
          ]);
        setMetrics(metricsRes);
        setEquityData(equityRes);
        setPnlDistribution(pnlRes);
        setAgents(agentsRes);
        setTrades(tradesRes);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to fetch data");
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[#a0a0a0] animate-pulse">加载仪表盘数据...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[#ff5252] font-bold">Error: {error}</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Metric Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <MetricCard
          title="总权益"
          value={metrics?.totalEquity?.toFixed(2) ?? "0.00"}
          change={metrics?.dailyPnlPercent}
          changeType={
            metrics && metrics.dailyPnl >= 0 ? "positive" : "negative"
          }
          icon={DollarSign}
        />
        <MetricCard
          title="日盈亏"
          value={metrics?.dailyPnl?.toFixed(2) ?? "0.00"}
          change={metrics?.dailyPnlPercent}
          changeType={
            metrics && metrics.dailyPnl >= 0 ? "positive" : "negative"
          }
          icon={TrendingUp}
        />
        <MetricCard
          title="总交易"
          value={metrics?.totalTrades ?? 0}
          icon={Activity}
        />
        <MetricCard
          title="活跃代理"
          value={`${metrics?.activeAgents ?? 0} / ${metrics?.totalAgents ?? 0}`}
          icon={Bot}
        />
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <EquityChart data={equityData} />
        </div>
        <div>
          <PnlDistributionChart data={pnlDistribution} />
        </div>
      </div>

      {/* Tables */}
      <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
        <div className="lg:col-span-3">
          <AgentTable agents={agents} />
        </div>
        <div className="lg:col-span-2">
          <TradeList trades={trades} />
        </div>
      </div>
    </div>
  );
}
