/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect, useRef } from 'react';
import { TradingTeam } from './simulation/TradingTeam';
import { AgentState } from './simulation/types';
import { Play, Pause, FastForward, Activity, Brain, Shield, TrendingUp, DollarSign, BookOpen, AlertTriangle, CheckCircle2, XCircle } from 'lucide-react';
import { cn } from './lib/utils';
import { motion } from 'motion/react';
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';

export default function App() {
  const [team] = useState(() => new TradingTeam());
  const [agents, setAgents] = useState<AgentState[]>([]);
  const [logs, setLogs] = useState<{ id: number; msg: string; time: number }[]>([]);
  const [history, setHistory] = useState<{ time: string; balance: number }[]>([]);
  const [memoryStats, setMemoryStats] = useState<{ symbol: string; winRate: number; failureRate: number; trades: number }[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  const [speed, setSpeed] = useState(1000);
  
  // Market Data State
  const [marketData, setMarketData] = useState<Record<string, any[]>>({});
  const [isLoadingData, setIsLoadingData] = useState(true);
  const [currentDateIndex, setCurrentDateIndex] = useState(0);
  const [currentTime, setCurrentTime] = useState(Date.now());
  
  const logIdRef = useRef(0);

  const symbols = ['NVDA', 'AAPL', 'MSFT', 'TSLA', 'BTC-USD'];

  const updateState = () => {
    const currentAgents = (Object.values(team.agents) as any[]).map(a => a.getState());
    setAgents(currentAgents);
    
    const totalBalance = currentAgents.reduce((sum, a) => sum + a.economicTracker.balance, 0);
    setHistory(prev => {
      const newHistory = [...prev, { 
        time: new Date(currentTime).toISOString().split('T')[0], 
        balance: totalBalance 
      }];
      return newHistory.slice(-50); // keep last 50 points
    });

    const stats = symbols.map(sym => ({
      symbol: sym,
      winRate: team.memorySystem.getRecentWinRate(sym),
      failureRate: team.memorySystem.getFailureRate(sym),
      trades: team.memorySystem.records.filter(r => r.symbol === sym).length
    }));
    setMemoryStats(stats);
  };

  useEffect(() => {
    const fetchMarketData = async () => {
      setIsLoadingData(true);
      const data: Record<string, any[]> = {};
      try {
        for (const sym of symbols) {
          const res = await fetch(`/api/market-data/${sym}?period1=2023-01-01`);
          if (res.ok) {
            data[sym] = await res.json();
          } else {
            console.error(`Failed to fetch data for ${sym}`);
            data[sym] = [];
          }
        }
        setMarketData(data);
        // Set initial time to the first available date of the first symbol
        if (data[symbols[0]] && data[symbols[0]].length > 0) {
          setCurrentTime(new Date(data[symbols[0]][0].date).getTime());
        }
      } catch (err) {
        console.error("Error fetching market data:", err);
      } finally {
        setIsLoadingData(false);
      }
    };
    
    fetchMarketData();
  }, []);

  useEffect(() => {
    updateState();
  }, [currentTime]); // Update state when time changes

  useEffect(() => {
    if (!isRunning || isLoadingData) return;

    const interval = setInterval(() => {
      // Advance to next day in the dataset
      setCurrentDateIndex(prev => {
        const nextIndex = prev + 1;
        
        // Find the maximum length among all symbols
        const maxLen = Math.max(...(Object.values(marketData) as any[][]).map(arr => arr.length));
        if (nextIndex >= maxLen) {
          setIsRunning(false); // Stop simulation if we run out of data
          return prev;
        }

        // Update current time based on the new index (using the first symbol's date as reference)
        const refSymbol = symbols.find(s => marketData[s] && marketData[s][nextIndex]);
        if (refSymbol) {
          const newTime = new Date(marketData[refSymbol][nextIndex].date).getTime();
          setCurrentTime(newTime);
          
          // Pick a random symbol to trade today
          const symbol = symbols[Math.floor(Math.random() * symbols.length)];
          const symbolData = marketData[symbol];
          
          if (symbolData && symbolData[nextIndex] && symbolData[nextIndex - 1]) {
            const currentPrice = symbolData[nextIndex].close;
            const prevPrice = symbolData[nextIndex - 1].close;
            // Calculate market trend (-1 to 1 based on daily return)
            // A 5% move would be 0.05. Let's scale it so 5% = 1.0
            const dailyReturn = (currentPrice - prevPrice) / prevPrice;
            const marketTrend = Math.max(-1, Math.min(1, dailyReturn * 20)); 
            
            team.simulateCycle(symbol, newTime, marketTrend, (msg) => {
              setLogs(prevLogs => {
                const newLogs = [{ id: logIdRef.current++, msg, time: newTime }, ...prevLogs];
                return newLogs.slice(0, 100);
              });
            });
          }
        }
        
        return nextIndex;
      });
      
    }, speed);

    return () => clearInterval(interval);
  }, [isRunning, speed, marketData, isLoadingData, team]);

  const totalBalance = agents.reduce((sum, a) => sum + a.economicTracker.balance, 0);
  const totalPnl = agents.reduce((sum, a) => sum + a.economicTracker.realizedPnl, 0);

  return (
    <div className="min-h-screen bg-[#0a0a0a] text-zinc-300 font-sans selection:bg-indigo-500/30">
      {/* Header */}
      <header className="border-b border-white/10 bg-black/50 backdrop-blur-md sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 h-16 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg bg-indigo-500/20 border border-indigo-500/50 flex items-center justify-center">
              <Activity className="w-5 h-5 text-indigo-400" />
            </div>
            <h1 className="font-semibold text-white tracking-tight">OpenClaw Trading</h1>
            <span className="px-2 py-0.5 rounded text-xs font-medium bg-zinc-800 text-zinc-400 border border-white/5">
              Simulation
            </span>
          </div>
          
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2 bg-zinc-900/50 rounded-lg p-1 border border-white/5">
              <button 
                onClick={() => setIsRunning(!isRunning)}
                disabled={isLoadingData}
                className={cn(
                  "px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-2",
                  isLoadingData ? "bg-zinc-800 text-zinc-500 cursor-not-allowed" :
                  isRunning ? "bg-amber-500/20 text-amber-400" : "bg-emerald-500/20 text-emerald-400"
                )}
              >
                {isLoadingData ? <Activity className="w-4 h-4 animate-spin" /> : isRunning ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
                {isLoadingData ? 'Loading Data...' : isRunning ? 'Pause' : 'Start'}
              </button>
              <button 
                onClick={() => setSpeed(s => s === 1000 ? 200 : 1000)}
                className={cn(
                  "px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-2",
                  speed === 200 ? "bg-indigo-500/20 text-indigo-400" : "hover:bg-white/5 text-zinc-400"
                )}
              >
                <FastForward className="w-4 h-4" />
                {speed === 200 ? 'Fast' : 'Normal'}
              </button>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 py-8 grid grid-cols-1 lg:grid-cols-12 gap-6">
        
        {/* Left Column: Overview & Agents */}
        <div className="lg:col-span-8 space-y-6">
          
          {/* Overview Cards */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="bg-zinc-900/50 border border-white/5 rounded-2xl p-5">
              <div className="flex items-center gap-3 text-zinc-400 mb-2">
                <DollarSign className="w-4 h-4" />
                <h3 className="text-sm font-medium">Total Capital</h3>
              </div>
              <div className="text-3xl font-semibold text-white">
                ${totalBalance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              </div>
            </div>
            
            <div className="bg-zinc-900/50 border border-white/5 rounded-2xl p-5">
              <div className="flex items-center gap-3 text-zinc-400 mb-2">
                <TrendingUp className="w-4 h-4" />
                <h3 className="text-sm font-medium">Realized PNL</h3>
              </div>
              <div className={cn(
                "text-3xl font-semibold",
                totalPnl >= 0 ? "text-emerald-400" : "text-red-400"
              )}>
                {totalPnl >= 0 ? '+' : ''}${totalPnl.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              </div>
            </div>

            <div className="bg-zinc-900/50 border border-white/5 rounded-2xl p-5">
              <div className="flex items-center gap-3 text-zinc-400 mb-2">
                <Brain className="w-4 h-4" />
                <h3 className="text-sm font-medium">Active Agents</h3>
              </div>
              <div className="text-3xl font-semibold text-white">
                {agents.filter(a => a.economicTracker.status !== '💀 bankrupt').length} / {agents.length}
              </div>
            </div>

            <div className="bg-zinc-900/50 border border-white/5 rounded-2xl p-5">
              <div className="flex items-center gap-3 text-zinc-400 mb-2">
                <BookOpen className="w-4 h-4" />
                <h3 className="text-sm font-medium">Memory Size</h3>
              </div>
              <div className="text-3xl font-semibold text-white">
                {team.memorySystem.getMemorySize()}
              </div>
            </div>
          </div>

          {/* Chart */}
          <div className="bg-zinc-900/50 border border-white/5 rounded-2xl p-5 h-64">
            <h3 className="text-sm font-medium text-zinc-400 mb-4">Capital History</h3>
            <div className="h-48 w-full">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={history}>
                  <XAxis dataKey="time" stroke="#52525b" fontSize={12} tickLine={false} axisLine={false} />
                  <YAxis 
                    domain={['auto', 'auto']} 
                    stroke="#52525b" 
                    fontSize={12} 
                    tickLine={false} 
                    axisLine={false}
                    tickFormatter={(val) => `$${(val/1000).toFixed(1)}k`}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#18181b', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                    itemStyle={{ color: '#a78bfa' }}
                    formatter={(value: number) => [`$${value.toFixed(2)}`, 'Balance']}
                  />
                  <Line type="monotone" dataKey="balance" stroke="#818cf8" strokeWidth={2} dot={false} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Agents Grid */}
          <div>
            <h2 className="text-lg font-medium text-white mb-4 flex items-center gap-2">
              <Shield className="w-5 h-5 text-indigo-400" />
              Agent Team
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {agents.map(agent => (
                <AgentCard key={agent.id} agent={agent} />
              ))}
            </div>
          </div>

          {/* Memory Bank */}
          <div>
            <h2 className="text-lg font-medium text-white mb-4 flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-indigo-400" />
              Memory Bank & UMP Status
            </h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
              {memoryStats.map(stat => (
                <div key={stat.symbol} className={cn(
                  "bg-zinc-900/50 border rounded-2xl p-4 transition-colors",
                  stat.failureRate > 0.6 ? "border-red-500/30 bg-red-500/5" : "border-white/5"
                )}>
                  <div className="flex items-center justify-between mb-2">
                    <h3 className="font-semibold text-white">{stat.symbol}</h3>
                    <span className="text-xs text-zinc-500">{stat.trades} trades</span>
                  </div>
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span className="text-zinc-400">Win Rate</span>
                      <span className={stat.winRate >= 0.5 ? "text-emerald-400" : "text-amber-400"}>
                        {(stat.winRate * 100).toFixed(0)}%
                      </span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-zinc-400">Failure Rate</span>
                      <span className={stat.failureRate > 0.6 ? "text-red-400 font-medium" : "text-zinc-300"}>
                        {(stat.failureRate * 100).toFixed(0)}%
                      </span>
                    </div>
                    {stat.failureRate > 0.6 && (
                      <div className="mt-2 text-xs text-red-400 flex items-center gap-1 bg-red-400/10 px-2 py-1 rounded">
                        <AlertTriangle className="w-3 h-3" />
                        UMP Blocked
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>

        </div>

        {/* Right Column: Activity Feed */}
        <div className="lg:col-span-4">
          <div className="bg-zinc-900/50 border border-white/5 rounded-2xl flex flex-col h-[calc(100vh-8rem)] sticky top-24">
            <div className="p-4 border-b border-white/5">
              <h2 className="text-lg font-medium text-white flex items-center gap-2">
                <Activity className="w-5 h-5 text-indigo-400" />
                Live Activity
              </h2>
            </div>
            <div className="flex-1 overflow-y-auto p-4 space-y-3 font-mono text-xs">
              {logs.length === 0 ? (
                <div className="text-zinc-500 text-center py-8">No activity yet. Start the simulation.</div>
              ) : (
                logs.map(log => (
                  <motion.div 
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    key={log.id} 
                    className="p-3 rounded-lg bg-black/40 border border-white/5 text-zinc-400 leading-relaxed"
                  >
                    <div className="text-zinc-600 mb-1">{new Date(log.time).toISOString().split('T')[0]}</div>
                    {log.msg}
                  </motion.div>
                ))
              )}
            </div>
          </div>
        </div>

      </main>
    </div>
  );
}

const AgentCard: React.FC<{ agent: AgentState }> = ({ agent }) => {
  const statusColors = {
    '🚀 thriving': 'text-emerald-400 bg-emerald-400/10 border-emerald-400/20',
    '💪 stable': 'text-blue-400 bg-blue-400/10 border-blue-400/20',
    '⚠️ struggling': 'text-amber-400 bg-amber-400/10 border-amber-400/20',
    '🔴 critical': 'text-red-400 bg-red-400/10 border-red-400/20',
    '💀 bankrupt': 'text-zinc-500 bg-zinc-500/10 border-zinc-500/20',
  };

  const statusColor = statusColors[agent.economicTracker.status] || 'text-zinc-400';

  return (
    <div className="bg-zinc-900/50 border border-white/5 rounded-2xl p-5 hover:bg-zinc-900/80 transition-colors">
      <div className="flex items-start justify-between mb-4">
        <div>
          <h3 className="font-medium text-white capitalize">{agent.id.replace('_', ' ')}</h3>
          <p className="text-xs text-zinc-500 capitalize">{agent.role} Role</p>
        </div>
        <div className={cn("px-2.5 py-1 rounded-full text-xs font-medium border", statusColor)}>
          {agent.economicTracker.status}
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 mb-4">
        <div>
          <div className="text-xs text-zinc-500 mb-1">Balance</div>
          <div className="font-mono text-sm text-zinc-200">
            ${agent.economicTracker.balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </div>
        </div>
        <div>
          <div className="text-xs text-zinc-500 mb-1">Win Rate</div>
          <div className="font-mono text-sm text-zinc-200">
            {(agent.winRate * 100).toFixed(1)}%
          </div>
        </div>
        <div>
          <div className="text-xs text-zinc-500 mb-1">Skill Level</div>
          <div className="font-mono text-sm text-zinc-200">
            {(agent.skillLevel * 100).toFixed(0)} / 100
          </div>
        </div>
        <div>
          <div className="text-xs text-zinc-500 mb-1">Token Costs</div>
          <div className="font-mono text-sm text-zinc-200">
            ${agent.economicTracker.tokenCosts.toFixed(2)}
          </div>
        </div>
      </div>

      {agent.learningStatus && (
        <div className="mt-4 p-3 rounded-lg bg-indigo-500/10 border border-indigo-500/20 flex items-start gap-3">
          <BookOpen className="w-4 h-4 text-indigo-400 shrink-0 mt-0.5" />
          <div>
            <div className="text-xs font-medium text-indigo-300">Currently Learning</div>
            <div className="text-xs text-indigo-400/70 capitalize">{agent.learningStatus.course.replace(/_/g, ' ')}</div>
          </div>
        </div>
      )}

      {agent.unlockedFactors.length > 0 && (
        <div className="mt-4 pt-4 border-t border-white/5">
          <div className="text-xs text-zinc-500 mb-2">Unlocked Factors</div>
          <div className="flex flex-wrap gap-1.5">
            {agent.unlockedFactors.map(factor => (
              <span key={factor} className="px-2 py-0.5 rounded text-[10px] font-medium bg-zinc-800 text-zinc-300 border border-white/5 capitalize">
                {factor.replace(/_/g, ' ')}
              </span>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

