/**
 * BotCard Component
 * Displays trading bot information including status, metrics, and control actions
 * Used to show individual bot cards in the trading agents dashboard
 */

import React from 'react';
import {
  Shield,
  Target,
  Rocket,
  TrendingUp,
  TrendingDown,
  Play,
  Pause,
  Square,
  Eye,
} from 'lucide-react';
import type { TradingBot, AgentType } from '../../../../types/tradingAgents.types';

/**
 * Props for BotCard component
 */
interface BotCardProps {
  /** Trading bot data to display */
  bot: TradingBot;

  /** Callback when user clicks to view bot details */
  onSelect?: (bot: TradingBot) => void;

  /** Callback when user starts the bot */
  onStart?: (botId: string) => void;

  /** Callback when user stops the bot */
  onStop?: (botId: string) => void;

  /** Whether actions are currently loading */
  loading?: boolean;
}

/**
 * BotCard Component
 * Displays a trading bot with its current status, metrics, and action buttons
 */
export const BotCard: React.FC<BotCardProps> = ({
  bot,
  onSelect,
  onStart,
  onStop,
  loading = false,
}) => {
  /**
   * Get icon component based on agent type
   */
  const getAgentIcon = (type: AgentType) => {
    const iconProps = { className: 'w-5 h-5 text-white' };
    switch (type) {
      case 'atlas':
        return <Shield {...iconProps} />;
      case 'orion':
        return <Target {...iconProps} />;
      case 'nova':
        return <Rocket {...iconProps} />;
      default:
        return <Target {...iconProps} />;
    }
  };

  /**
   * Get background color for agent icon based on type
   */
  const getAgentColor = (type: AgentType): string => {
    switch (type) {
      case 'atlas':
        return 'bg-blue-600';
      case 'orion':
        return 'bg-purple-600';
      case 'nova':
        return 'bg-orange-600';
      default:
        return 'bg-gray-600';
    }
  };

  /**
   * Get status badge styling based on bot status
   */
  const getStatusStyle = (status: string) => {
    switch (status) {
      case 'running':
        return 'bg-green-900/50 text-green-400 border-green-700';
      case 'stopped':
        return 'bg-gray-900/50 text-gray-400 border-gray-700';
      case 'error':
        return 'bg-red-900/50 text-red-400 border-red-700';
      case 'paused':
        return 'bg-yellow-900/50 text-yellow-400 border-yellow-700';
      default:
        return 'bg-gray-900/50 text-gray-400 border-gray-700';
    }
  };

  /**
   * Get risk level text and color based on agent type
   */
  const getRiskBadge = (type: AgentType) => {
    switch (type) {
      case 'atlas':
        return { label: 'Conservative', color: 'text-green-400' };
      case 'orion':
        return { label: 'Moderate', color: 'text-yellow-400' };
      case 'nova':
        return { label: 'Aggressive', color: 'text-red-400' };
      default:
        return { label: 'Unknown', color: 'text-gray-400' };
    }
  };

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

  /**
   * Format percentage values
   */
  const formatPercentage = (value: number): string => {
    return `${value.toFixed(1)}%`;
  };

  const riskBadge = getRiskBadge(bot.name);
  const isProfitable = bot.todayPnl >= 0;
  const winRate = bot.metrics?.win_rate ?? 0;

  return (
    <div className="bg-gray-900 rounded-lg p-4 border border-gray-700 hover:border-gray-600 transition-colors">
      {/* Header Section */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          {/* Agent Icon */}
          <div className={`p-2 rounded-lg ${getAgentColor(bot.name)}`}>
            {getAgentIcon(bot.name)}
          </div>

          {/* Agent Name and Risk Level */}
          <div>
            <h3 className="text-white font-bold">{bot.displayName}</h3>
            <span className={`text-xs ${riskBadge.color}`}>{riskBadge.label}</span>
          </div>
        </div>

        {/* Status Badge */}
        <div
          className={`px-2.5 py-1 rounded-full text-xs font-semibold border ${getStatusStyle(bot.status)}`}
        >
          {bot.status.charAt(0).toUpperCase() + bot.status.slice(1)}
        </div>
      </div>

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

      {/* Main Metrics Grid */}
      <div className="grid grid-cols-2 gap-3 mb-4">
        {/* P&L Card */}
        <div className="bg-gray-800 rounded-lg p-3">
          <span className="text-gray-500 text-xs block mb-1">Today's P&L</span>
          <div className="flex items-center gap-1">
            {isProfitable ? (
              <TrendingUp className="w-4 h-4 text-green-400" />
            ) : (
              <TrendingDown className="w-4 h-4 text-red-400" />
            )}
            <p
              className={`text-xl font-bold ${isProfitable ? 'text-green-400' : 'text-red-400'}`}
            >
              {formatCurrency(bot.todayPnl)}
            </p>
          </div>
        </div>

        {/* Win Rate Card */}
        <div className="bg-gray-800 rounded-lg p-3">
          <span className="text-gray-500 text-xs block mb-1">Win Rate</span>
          <p className="text-xl font-bold text-blue-400">{formatPercentage(winRate)}</p>
        </div>
      </div>

      {/* Secondary Stats */}
      <div className="grid grid-cols-3 gap-2 mb-4">
        {/* Positions */}
        <div className="text-center">
          <span className="text-gray-500 text-xs block mb-1">Positions</span>
          <p className="text-white font-semibold">{bot.positions}</p>
        </div>

        {/* Equity */}
        <div className="text-center">
          <span className="text-gray-500 text-xs block mb-1">Equity</span>
          <p className="text-white font-semibold text-sm">{formatCurrency(bot.equity)}</p>
        </div>

        {/* Total Trades */}
        <div className="text-center">
          <span className="text-gray-500 text-xs block mb-1">Trades</span>
          <p className="text-white font-semibold">{bot.metrics?.total_trades ?? 0}</p>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex gap-2 pt-3 border-t border-gray-700">
        {/* View Details Button */}
        {onSelect && (
          <button
            onClick={() => onSelect(bot)}
            className="flex-1 flex items-center justify-center gap-1.5 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded text-xs font-semibold transition-colors"
            title="View bot details"
          >
            <Eye className="w-3.5 h-3.5" />
            Details
          </button>
        )}

        {/* Start/Stop Button */}
        {bot.status === 'running' || bot.status === 'paused' ? (
          onStop && (
            <button
              onClick={() => onStop(bot.id)}
              disabled={loading}
              className="flex-1 flex items-center justify-center gap-1.5 py-2 bg-red-700 hover:bg-red-600 text-white rounded text-xs font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              title="Stop bot"
            >
              <Square className="w-3.5 h-3.5" />
              Stop
            </button>
          )
        ) : (
          onStart && (
            <button
              onClick={() => onStart(bot.id)}
              disabled={loading}
              className="flex-1 flex items-center justify-center gap-1.5 py-2 bg-green-700 hover:bg-green-600 text-white rounded text-xs font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              title="Start bot"
            >
              <Play className="w-3.5 h-3.5" />
              Start
            </button>
          )
        )}

        {/* Pause Button (only when running) */}
        {bot.status === 'running' && onStop && (
          <button
            onClick={() => onStop(bot.id)}
            disabled={loading}
            className="flex items-center justify-center gap-1.5 px-3 py-2 bg-yellow-700 hover:bg-yellow-600 text-white rounded text-xs font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            title="Pause bot"
          >
            <Pause className="w-3.5 h-3.5" />
          </button>
        )}
      </div>
    </div>
  );
};

export default BotCard;
