/**
 * Trading Agents Page
 * Manage and monitor trading agents (Atlas, Orion, Nova)
 */

import { useState, useEffect } from 'react';
import {
  UserGroupIcon,
  ArrowPathIcon,
  ChartBarIcon,
  CurrencyDollarIcon,
  SignalIcon,
} from '@heroicons/react/24/solid';
import { AgentStatsCard } from '../components';
import {
  getAgents,
  updateAgentStatus,
  getSignalHistory,
  type AgentPerformance,
  type SignalHistory,
} from '../../../services/adminService';

export default function AgentsPage() {
  const [agents, setAgents] = useState<AgentPerformance[]>([]);
  const [signals, setSignals] = useState<SignalHistory[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedAgent, setSelectedAgent] = useState<string | null>(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const [agentsData, signalsData] = await Promise.all([
        getAgents(),
        getSignalHistory({ limit: 20 }),
      ]);
      setAgents(Array.isArray(agentsData) ? agentsData : []);
      setSignals(Array.isArray(signalsData) ? signalsData : []);
    } catch (error) {
      console.error('Error loading data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = async (agentId: string, newStatus: 'active' | 'paused' | 'stopped') => {
    const success = await updateAgentStatus(agentId, newStatus);
    if (success) {
      setAgents(prev =>
        prev.map(a =>
          a.agent_id === agentId ? { ...a, status: newStatus } : a
        )
      );
    }
  };

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2,
    }).format(value);
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return 'N/A';
    return new Date(dateString).toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const totalPnL = agents.reduce((acc, a) => acc + (a.total_pnl || 0), 0);
  const totalTrades = agents.reduce((acc, a) => acc + (a.total_trades || 0), 0);
  const totalSignals = agents.reduce((acc, a) => acc + (a.total_signals || 0), 0);
  const avgWinRate = agents.length > 0
    ? agents.reduce((acc, a) => acc + (a.win_rate || 0), 0) / agents.length
    : 0;

  const filteredSignals = selectedAgent
    ? signals.filter(s => s.agent_name === selectedAgent)
    : signals;

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-500"></div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-purple-600 rounded-lg">
            <UserGroupIcon className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">Trading Agents</h1>
            <p className="text-gray-400">Monitor and control automated trading agents</p>
          </div>
        </div>
        <button
          onClick={loadData}
          className="flex items-center gap-2 px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg transition-colors"
        >
          <ArrowPathIcon className="w-4 h-4" />
          Refresh
        </button>
      </div>

      {/* Summary Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <div className="flex items-center gap-2 mb-2">
            <CurrencyDollarIcon className="w-5 h-5 text-green-400" />
            <span className="text-gray-400 text-sm">Total P&L</span>
          </div>
          <p className={`text-2xl font-bold ${totalPnL >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            {formatCurrency(totalPnL)}
          </p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <div className="flex items-center gap-2 mb-2">
            <ChartBarIcon className="w-5 h-5 text-blue-400" />
            <span className="text-gray-400 text-sm">Avg Win Rate</span>
          </div>
          <p className="text-2xl font-bold text-blue-400">
            {(avgWinRate * 100).toFixed(1)}%
          </p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <div className="flex items-center gap-2 mb-2">
            <SignalIcon className="w-5 h-5 text-purple-400" />
            <span className="text-gray-400 text-sm">Total Signals</span>
          </div>
          <p className="text-2xl font-bold text-purple-400">{totalSignals}</p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <div className="flex items-center gap-2 mb-2">
            <UserGroupIcon className="w-5 h-5 text-orange-400" />
            <span className="text-gray-400 text-sm">Total Trades</span>
          </div>
          <p className="text-2xl font-bold text-orange-400">{totalTrades}</p>
        </div>
      </div>

      {/* Agents Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {agents.map((agent) => (
          <AgentStatsCard
            key={agent.agent_id}
            agent={agent}
            onStatusChange={handleStatusChange}
            expanded
          />
        ))}
      </div>

      {/* Empty Agents State */}
      {agents.length === 0 && (
        <div className="bg-gray-800 rounded-lg p-8 border border-gray-700 text-center">
          <UserGroupIcon className="w-12 h-12 text-gray-600 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-white mb-2">No Trading Agents</h3>
          <p className="text-gray-400">Trading agents have not been configured yet.</p>
        </div>
      )}

      {/* Recent Signals */}
      <div className="bg-gray-800 rounded-lg p-5 border border-gray-700">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-bold text-white">Recent Signals</h2>
          <div className="flex gap-2">
            <button
              onClick={() => setSelectedAgent(null)}
              className={`px-3 py-1 rounded text-sm ${
                !selectedAgent ? 'bg-primary-600 text-white' : 'bg-gray-700 text-gray-300'
              }`}
            >
              All
            </button>
            {agents.map(a => (
              <button
                key={a.agent_id}
                onClick={() => setSelectedAgent(a.name)}
                className={`px-3 py-1 rounded text-sm ${
                  selectedAgent === a.name ? 'bg-primary-600 text-white' : 'bg-gray-700 text-gray-300'
                }`}
              >
                {a.name}
              </button>
            ))}
          </div>
        </div>

        {/* Signals Table */}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="text-left text-gray-400 text-sm border-b border-gray-700">
                <th className="pb-3 font-medium">Agent</th>
                <th className="pb-3 font-medium">Symbol</th>
                <th className="pb-3 font-medium">Direction</th>
                <th className="pb-3 font-medium">Entry</th>
                <th className="pb-3 font-medium">TP / SL</th>
                <th className="pb-3 font-medium">Confidence</th>
                <th className="pb-3 font-medium">Status</th>
                <th className="pb-3 font-medium">Result</th>
                <th className="pb-3 font-medium">Time</th>
              </tr>
            </thead>
            <tbody>
              {filteredSignals.map((signal) => (
                <tr key={signal.signal_id} className="border-b border-gray-700/50 text-sm">
                  <td className="py-3">
                    <span className={`font-semibold ${
                      signal.agent_name === 'Atlas' ? 'text-blue-400' :
                      signal.agent_name === 'Orion' ? 'text-purple-400' :
                      'text-orange-400'
                    }`}>
                      {signal.agent_name}
                    </span>
                  </td>
                  <td className="py-3 text-white font-semibold">{signal.symbol}</td>
                  <td className="py-3">
                    <span className={`px-2 py-1 rounded text-xs font-semibold ${
                      signal.direction === 'long'
                        ? 'bg-green-900/50 text-green-400'
                        : 'bg-red-900/50 text-red-400'
                    }`}>
                      {signal.direction.toUpperCase()}
                    </span>
                  </td>
                  <td className="py-3 text-white">{signal.entry_price?.toFixed(2)}</td>
                  <td className="py-3 text-gray-400">
                    <span className="text-green-400">{signal.take_profit?.toFixed(2)}</span>
                    {' / '}
                    <span className="text-red-400">{signal.stop_loss?.toFixed(2)}</span>
                  </td>
                  <td className="py-3 text-blue-400">
                    {((signal.confidence || 0) * 100).toFixed(0)}%
                  </td>
                  <td className="py-3">
                    <span className={`px-2 py-1 rounded text-xs ${
                      signal.status === 'active' ? 'bg-blue-900/50 text-blue-400' :
                      signal.status === 'completed' ? 'bg-gray-700 text-gray-400' :
                      'bg-yellow-900/50 text-yellow-400'
                    }`}>
                      {signal.status}
                    </span>
                  </td>
                  <td className="py-3">
                    {signal.result && (
                      <span className={`font-semibold ${
                        signal.result === 'win' ? 'text-green-400' :
                        signal.result === 'loss' ? 'text-red-400' :
                        'text-gray-400'
                      }`}>
                        {signal.result === 'win' ? '+' : signal.result === 'loss' ? '-' : ''}
                        {signal.profit_loss ? formatCurrency(Math.abs(signal.profit_loss)) : signal.result}
                      </span>
                    )}
                  </td>
                  <td className="py-3 text-gray-400">{formatDate(signal.created_at)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filteredSignals.length === 0 && (
          <div className="text-center py-8 text-gray-500">
            No signals found
          </div>
        )}
      </div>
    </div>
  );
}
