/**
 * AgentCard Component
 * Displays individual agent performance statistics and control buttons
 */

import {
  UserGroupIcon,
  PlayIcon,
  PauseIcon,
  StopIcon,
  ArrowTrendingUpIcon,
  ArrowTrendingDownIcon,
} from '@heroicons/react/24/solid';
import type { AgentPerformance } from '../../../../services/adminService';

interface AgentCardProps {
  agent: AgentPerformance;
  onStatusChange?: (agentId: string, newStatus: 'active' | 'paused' | 'stopped') => void;
}

export function AgentCard({ agent, onStatusChange }: AgentCardProps) {
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return 'bg-green-900/50 text-green-400 border-green-700';
      case 'paused':
        return 'bg-yellow-900/50 text-yellow-400 border-yellow-700';
      default:
        return 'bg-red-900/50 text-red-400 border-red-700';
    }
  };

  const getAgentColor = (name: string) => {
    const colors: Record<string, string> = {
      Atlas: 'bg-blue-600',
      Orion: 'bg-purple-600',
      Nova: 'bg-orange-600',
    };
    return colors[name] || 'bg-gray-600';
  };

  const getRiskBadge = (name: string) => {
    const risks: Record<string, { label: string; color: string }> = {
      Atlas: { label: 'Conservative', color: 'text-green-400' },
      Orion: { label: 'Moderate', color: 'text-yellow-400' },
      Nova: { label: 'Aggressive', color: 'text-red-400' },
    };
    return risks[name] || { label: 'Unknown', color: 'text-gray-400' };
  };

  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).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const riskBadge = getRiskBadge(agent.name);

  return (
    <div className="bg-gray-900 rounded-lg p-4 border border-gray-700 hover:border-gray-600 transition-colors">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${getAgentColor(agent.name)}`}>
            <UserGroupIcon className="w-5 h-5 text-white" />
          </div>
          <div>
            <h3 className="text-white font-bold">{agent.name}</h3>
            <span className={`text-xs ${riskBadge.color}`}>{riskBadge.label}</span>
          </div>
        </div>
        <div className={`px-2.5 py-1 rounded-full text-xs font-semibold border ${getStatusColor(agent.status)}`}>
          {agent.status.charAt(0).toUpperCase() + agent.status.slice(1)}
        </div>
      </div>

      {/* Description */}
      {agent.description && (
        <p className="text-gray-400 text-xs mb-4 line-clamp-2">{agent.description}</p>
      )}

      {/* Main Stats */}
      <div className="grid grid-cols-2 gap-3 mb-4">
        <div className="bg-gray-800 rounded-lg p-3">
          <span className="text-gray-500 text-xs">Win Rate</span>
          <p className="text-xl font-bold text-green-400">
            {((agent.win_rate || 0) * 100).toFixed(1)}%
          </p>
        </div>
        <div className="bg-gray-800 rounded-lg p-3">
          <span className="text-gray-500 text-xs">Total P&L</span>
          <div className="flex items-center gap-1">
            {(agent.total_pnl || 0) >= 0 ? (
              <ArrowTrendingUpIcon className="w-4 h-4 text-green-400" />
            ) : (
              <ArrowTrendingDownIcon className="w-4 h-4 text-red-400" />
            )}
            <p className={`text-xl font-bold ${(agent.total_pnl || 0) >= 0 ? 'text-green-400' : 'text-red-400'}`}>
              {formatCurrency(agent.total_pnl || 0)}
            </p>
          </div>
        </div>
      </div>

      {/* Secondary Stats */}
      <div className="grid grid-cols-3 gap-2 mb-4">
        <div className="text-center">
          <span className="text-gray-500 text-xs">Trades</span>
          <p className="text-white font-semibold">{agent.total_trades || 0}</p>
        </div>
        <div className="text-center">
          <span className="text-gray-500 text-xs">Signals</span>
          <p className="text-white font-semibold">{agent.total_signals || 0}</p>
        </div>
        <div className="text-center">
          <span className="text-gray-500 text-xs">Avg Profit</span>
          <p className={`font-semibold ${(agent.avg_profit_per_trade || 0) >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            {formatCurrency(agent.avg_profit_per_trade || 0)}
          </p>
        </div>
      </div>

      {/* Footer */}
      <div className="flex items-center justify-between text-xs text-gray-500 mb-3 border-t border-gray-700 pt-3">
        <span>Confidence: {((agent.avg_confidence || 0) * 100).toFixed(0)}%</span>
        <span>Last signal: {formatDate(agent.last_signal_at)}</span>
      </div>

      {/* Control Buttons */}
      {onStatusChange && (
        <div className="flex gap-2">
          {agent.status !== 'active' && (
            <button
              onClick={() => onStatusChange(agent.agent_id, 'active')}
              className="flex-1 flex items-center justify-center gap-1 py-2 bg-green-700 hover:bg-green-600 text-white rounded text-xs font-semibold transition-colors"
              title="Start agent"
            >
              <PlayIcon className="w-3 h-3" />
              Start
            </button>
          )}
          {agent.status === 'active' && (
            <button
              onClick={() => onStatusChange(agent.agent_id, 'paused')}
              className="flex-1 flex items-center justify-center gap-1 py-2 bg-yellow-700 hover:bg-yellow-600 text-white rounded text-xs font-semibold transition-colors"
              title="Pause agent"
            >
              <PauseIcon className="w-3 h-3" />
              Pause
            </button>
          )}
          {agent.status !== 'stopped' && (
            <button
              onClick={() => onStatusChange(agent.agent_id, 'stopped')}
              className="flex-1 flex items-center justify-center gap-1 py-2 bg-red-700 hover:bg-red-600 text-white rounded text-xs font-semibold transition-colors"
              title="Stop agent"
            >
              <StopIcon className="w-3 h-3" />
              Stop
            </button>
          )}
        </div>
      )}
    </div>
  );
}
