"use client";

import { useEffect, useState, use } from "react";
import {
  ArrowLeft,
  Play,
  Pause,
  Wallet,
  TrendingUp,
  Target,
  Award,
  Activity,
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";

import { EquityChart } from "@/components/ui/EquityChart";
import { getAgent } from "@/api/agents";
import { getTrades } from "@/api/trades";
import { getPositions } from "@/api/positions";
import { getEquityCurve } from "@/api/metrics";
import type {
  AgentStatus,
  TradeRecord,
  Position,
  EquityPoint,
} from "@/types/models";
import { cn } from "@/lib/utils";

interface AgentDetailData extends AgentStatus {
  initialCapital: number;
  skillLevel: number;
  unlockedFactors: string[];
}

export default function AgentDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const [agent, setAgent] = useState<AgentDetailData | null>(null);
  const [trades, setTrades] = useState<TradeRecord[]>([]);
  const [positions, setPositions] = useState<Position[]>([]);
  const [equityData, setEquityData] = useState<EquityPoint[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isPaused, setIsPaused] = useState(false);

  useEffect(() => {
    async function fetchData() {
      if (!id) return;
      try {
        setLoading(true);
        const [agentRes, tradesRes, positionsRes, equityRes] = await Promise.all([
          getAgent(id),
          getTrades({ agentId: id, limit: 50 }),
          getPositions(),
          getEquityCurve(),
        ]);

        setAgent({
          ...agentRes,
          initialCapital: 10000,
          skillLevel: Math.floor(Math.random() * 5) + 1,
          unlockedFactors: [
            "Trend Analysis",
            "Mean Reversion",
            "Breakout Logic",
            "Momentum X",
          ],
        });
        setTrades(tradesRes);
        setPositions(positionsRes.filter((p) => p.symbol === agentRes.symbol));
        setEquityData(equityRes);
        setIsPaused(agentRes.status === "paused");
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to fetch data");
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, [id]);

  const handlePauseResume = () => {
    setIsPaused(!isPaused);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[#a0a0a0] animate-pulse font-bold uppercase tracking-widest">Accessing agent neural state...</div>
      </div>
    );
  }

  if (error || !agent) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[#ff5252] font-bold">ERROR: {error || "Agent Not Found"}</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Back Button */}
      <Link
        href="/agents"
        className="inline-flex items-center gap-2 border border-[#2c2c2c] text-[#a0a0a0] hover:text-[#e1e1e1] px-4 py-2 rounded-lg text-xs font-black uppercase tracking-widest transition-all"
      >
        <ArrowLeft className="w-4 h-4" />
        Return to Matrix
      </Link>

      {/* Header with Actions */}
      <div className="flex items-center justify-between bg-[#1e1e1e] p-6 rounded-2xl border border-[#2c2c2c] shadow-xl">
        <div className="flex items-center gap-6">
          <div className="w-16 h-16 bg-[#00ffcc] rounded-2xl flex items-center justify-center text-[#121212] font-black text-2xl shadow-[0_0_20px_rgba(0,255,204,0.3)]">
            {agent.name.charAt(0)}
          </div>
          <div>
            <h1 className="text-2xl font-black text-[#e1e1e1] tracking-tight">{agent.name}</h1>
            <p className="text-[#666666] text-[10px] font-mono uppercase tracking-widest mt-1">NODE ID: {agent.id}</p>
          </div>
        </div>
        <button
          onClick={handlePauseResume}
          className={cn(
            "px-6 py-3 rounded-xl text-xs font-black uppercase tracking-widest transition-all shadow-lg flex items-center gap-2",
            isPaused
              ? "bg-[#00ffcc] text-[#121212] hover:bg-[#00e6b8]"
              : "bg-[#ffb74d] text-[#121212] hover:bg-[#ffa726]"
          )}
        >
          {isPaused ? (
            <>
              <Play className="w-4 h-4" />
              Activate Node
            </>
          ) : (
            <>
              <Pause className="w-4 h-4" />
              Suspend Node
            </>
          )}
        </button>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label: "Equity Balance", value: `$${agent.profitLoss.toFixed(2)}`, icon: Wallet, color: agent.profitLoss >= 0 ? "text-[#00ffcc]" : "text-[#ff5252]", bg: "bg-blue-500/10" },
          { label: "Core Capital", value: `$${agent.initialCapital.toFixed(2)}`, icon: Target, color: "text-[#e1e1e1]", bg: "bg-purple-500/10" },
          { label: "Execution Win Rate", value: `${agent.profitLossPercent.toFixed(2)}%`, icon: TrendingUp, color: "text-[#00ffcc]", bg: "bg-[#00ffcc]/10" },
          { label: "Neural Level", value: `Lv.${agent.skillLevel}`, icon: Award, color: "text-[#ffb74d]", bg: "bg-[#ffb74d]/10" },
        ].map((stat, i) => (
          <div key={i} className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-2xl p-5 shadow-lg group hover:border-[#2c2c2c] transition-all">
            <div className="flex items-center gap-4">
              <div className={cn("p-3 rounded-xl group-hover:scale-110 transition-transform", stat.bg)}>
                <stat.icon className={cn("w-5 h-5", stat.color)} />
              </div>
              <div>
                <p className="text-[#666666] text-[10px] font-black uppercase tracking-widest">{stat.label}</p>
                <p className={cn("text-lg font-black tracking-tight", stat.color)}>
                  {stat.value}
                </p>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Equity Chart */}
      <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-2xl p-6 shadow-xl">
        <h3 className="text-sm font-black text-[#e1e1e1] uppercase tracking-widest mb-6 flex items-center gap-2">
          <Activity className="w-4 h-4 text-[#00ffcc]" />
          Performance Telemetry
        </h3>
        <EquityChart data={equityData} height={350} />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Unlocked Factors */}
        <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-2xl p-6 shadow-xl">
          <h3 className="text-sm font-black text-[#e1e1e1] uppercase tracking-widest mb-6 flex items-center gap-2">
            <Activity className="w-4 h-4 text-[#00ffcc]" />
            Unlocked Neural Factors
          </h3>
          <div className="flex flex-wrap gap-2">
            {agent.unlockedFactors.map((factor) => (
              <span
                key={factor}
                className="px-4 py-2 bg-[#121212] border border-[#2c2c2c] text-[#a0a0a0] rounded-xl text-[10px] font-black uppercase tracking-widest hover:border-[#00ffcc]/30 transition-all cursor-default"
              >
                {factor}
              </span>
            ))}
          </div>
        </div>

        {/* Current Positions */}
        <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-2xl p-6 shadow-xl">
          <h3 className="text-sm font-black text-[#e1e1e1] uppercase tracking-widest mb-6">Current Open Risk</h3>
          {positions.length === 0 ? (
            <div className="py-12 text-center text-[#666666] font-bold uppercase tracking-widest italic border border-dashed border-[#2c2c2c] rounded-xl">No active exposure</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-[#2c2c2c]">
                    <th className="text-left py-3 px-2 text-[10px] font-black text-[#666666] uppercase tracking-widest">Asset</th>
                    <th className="text-left py-3 px-2 text-[10px] font-black text-[#666666] uppercase tracking-widest">Side</th>
                    <th className="text-right py-3 px-2 text-[10px] font-black text-[#666666] uppercase tracking-widest">Qty</th>
                    <th className="text-right py-3 px-2 text-[10px] font-black text-[#666666] uppercase tracking-widest">Unrealized P&L</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#2c2c2c]">
                  {positions.map((pos) => (
                    <tr key={pos.id} className="hover:bg-[#121212]/50">
                      <td className="py-4 px-2 text-sm font-black text-[#e1e1e1]">{pos.symbol}</td>
                      <td className="py-4 px-2">
                        <span className={cn(
                          "px-2 py-0.5 rounded text-[10px] font-black uppercase tracking-tighter",
                          pos.side === "long" ? "bg-[#00ffcc]/10 text-[#00ffcc]" : "bg-[#ff5252]/10 text-[#ff5252]"
                        )}>
                          {pos.side}
                        </span>
                      </td>
                      <td className="py-4 px-2 text-right text-sm font-bold text-[#e1e1e1]">{pos.quantity}</td>
                      <td className={cn(
                        "py-4 px-2 text-right text-sm font-black italic tracking-tighter",
                        pos.unrealizedPnl >= 0 ? "text-[#00ffcc]" : "text-[#ff5252]"
                      )}>
                        {pos.unrealizedPnl >= 0 ? "+" : ""}{pos.unrealizedPnl.toFixed(2)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {/* Trade History */}
      <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-2xl p-6 shadow-xl">
        <h3 className="text-sm font-black text-[#e1e1e1] uppercase tracking-widest mb-6">Execution Log</h3>
        {trades.length === 0 ? (
          <div className="py-12 text-center text-[#666666] font-bold uppercase tracking-widest italic border border-dashed border-[#2c2c2c] rounded-xl">Empty execution history</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-[#2c2c2c]">
                  <th className="text-left py-4 px-4 text-[10px] font-black text-[#666666] uppercase tracking-widest">Time</th>
                  <th className="text-left py-4 px-4 text-[10px] font-black text-[#666666] uppercase tracking-widest">Asset</th>
                  <th className="text-left py-4 px-4 text-[10px] font-black text-[#666666] uppercase tracking-widest">Side</th>
                  <th className="text-right py-4 px-4 text-[10px] font-black text-[#666666] uppercase tracking-widest">Qty</th>
                  <th className="text-right py-4 px-4 text-[10px] font-black text-[#666666] uppercase tracking-widest">Price</th>
                  <th className="text-right py-4 px-4 text-[10px] font-black text-[#666666] uppercase tracking-widest">P&L</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#2c2c2c]">
                {trades.map((trade) => (
                  <tr key={trade.id} className="hover:bg-[#121212]/50 group transition-colors">
                    <td className="py-4 px-4 text-[10px] font-bold text-[#666666] uppercase tracking-tighter">
                      {new Date(trade.timestamp).toLocaleString()}
                    </td>
                    <td className="py-4 px-4 text-sm font-black text-[#e1e1e1] group-hover:text-[#00ffcc] transition-colors">{trade.symbol}</td>
                    <td className="py-4 px-4">
                      <span className={cn(
                        "px-2 py-0.5 rounded text-[10px] font-black uppercase tracking-widest italic shadow-sm",
                        trade.side === "buy" ? "bg-[#00ffcc]/10 text-[#00ffcc]" : "bg-[#ff5252]/10 text-[#ff5252]"
                      )}>
                        {trade.side}
                      </span>
                    </td>
                    <td className="py-4 px-4 text-right text-sm font-bold text-[#e1e1e1]">{trade.quantity}</td>
                    <td className="py-4 px-4 text-right text-sm font-mono text-[#e1e1e1]">{trade.price.toFixed(2)}</td>
                    <td className={cn(
                      "py-4 px-4 text-right text-sm font-black italic tracking-tighter",
                      trade.pnl && trade.pnl >= 0 ? "text-[#00ffcc]" : trade.pnl && trade.pnl < 0 ? "text-[#ff5252]" : "text-[#666666]"
                    )}>
                      {trade.pnl ? `${trade.pnl >= 0 ? "+" : ""}${trade.pnl.toFixed(2)}` : "-"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
