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

import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, RefreshCw, Loader2, Bot, AlertCircle, Shield, Target, Rocket } from 'lucide-react';
import { useBots, useStartBot, useStopBot } from '../hooks/useBots';
import { BotCard } from '../components/agents/BotCard';
import { CreateBotModal } from '../components/agents/CreateBotModal';
import type { TradingBot as AgentBot } from '../../../types/tradingAgents.types';
import type { TradingBot, BotStatus } from '../../../services/bots.service';

export default function AgentsPage() {
  const navigate = useNavigate();
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [statusFilter, setStatusFilter] = useState<BotStatus | 'all'>('all');

  const { data: bots, isLoading, error, refetch } = useBots(
    statusFilter !== 'all' ? { status: statusFilter } : undefined
  );

  const startMutation = useStartBot();
  const stopMutation = useStopBot();

  // Handlers
  const handleStartBot = async (botId: string) => {
    try {
      await startMutation.mutateAsync(botId);
    } catch (err) {
      console.error('Failed to start bot:', err);
    }
  };

  const handleStopBot = async (botId: string) => {
    try {
      await stopMutation.mutateAsync(botId);
    } catch (err) {
      console.error('Failed to stop bot:', err);
    }
  };

  const handleSelectBot = (bot: AgentBot | TradingBot) => {
    navigate(`/trading/agents/${bot.id}`);
  };

  // Map TradingBot to the format expected by BotCard
  const mapBotForCard = (bot: TradingBot): AgentBot => ({
    id: bot.id,
    name: (bot.strategyType as 'atlas' | 'orion' | 'nova') || 'atlas',
    displayName: bot.name,
    description: `${bot.strategyType || 'Custom'} - ${bot.symbols.join(', ')}`,
    status: mapStatus(bot.status),
    equity: bot.currentCapital,
    positions: 0, // Would need positions data
    todayPnl: bot.totalProfitLoss,
    metrics: {
      total_trades: bot.totalTrades,
      winning_trades: bot.winningTrades,
      losing_trades: bot.totalTrades - bot.winningTrades,
      win_rate: bot.winRate,
      total_profit: bot.totalProfitLoss > 0 ? bot.totalProfitLoss : 0,
      total_loss: bot.totalProfitLoss < 0 ? Math.abs(bot.totalProfitLoss) : 0,
      net_pnl: bot.totalProfitLoss,
      max_drawdown: bot.maxDrawdownPct,
      current_drawdown: 0,
    },
  });

  const mapStatus = (status: BotStatus): 'running' | 'paused' | 'stopped' | 'error' | 'idle' | 'unavailable' => {
    switch (status) {
      case 'active': return 'running';
      case 'paused': return 'paused';
      case 'stopped': return 'stopped';
      case 'error': return 'error';
      default: return 'stopped';
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Trading Agents</h1>
          <p className="text-gray-400 mt-1">
            Manage your automated trading bots: Atlas, Orion, and Nova
          </p>
        </div>
        <div className="flex items-center gap-3">
          {/* Status Filter */}
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value as BotStatus | 'all')}
            className="px-4 py-2 bg-gray-700 text-white border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="all">All Status</option>
            <option value="active">Active</option>
            <option value="paused">Paused</option>
            <option value="stopped">Stopped</option>
            <option value="error">Error</option>
          </select>

          {/* Refresh Button */}
          <button
            onClick={() => refetch()}
            disabled={isLoading}
            className="flex items-center gap-2 px-4 py-2 bg-gray-700 hover:bg-gray-600 disabled:bg-gray-800 text-white rounded-lg transition-colors"
          >
            <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
          </button>

          {/* Create Bot Button */}
          <button
            onClick={() => setShowCreateModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
          >
            <Plus className="w-4 h-4" />
            <span>Create Bot</span>
          </button>
        </div>
      </div>

      {/* Strategy Templates Info */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <StrategyInfoCard
          icon={<Shield className="w-5 h-5" />}
          name="Atlas"
          description="Trend Following"
          risk="Medium"
          color="blue"
        />
        <StrategyInfoCard
          icon={<Target className="w-5 h-5" />}
          name="Orion"
          description="Mean Reversion"
          risk="Low"
          color="purple"
        />
        <StrategyInfoCard
          icon={<Rocket className="w-5 h-5" />}
          name="Nova"
          description="Breakout"
          risk="High"
          color="orange"
        />
      </div>

      {/* Loading State */}
      {isLoading && (
        <div className="flex items-center justify-center py-12">
          <div className="flex items-center gap-3 text-gray-400">
            <Loader2 className="w-6 h-6 animate-spin" />
            <span>Loading bots...</span>
          </div>
        </div>
      )}

      {/* Error State */}
      {error && (
        <div className="bg-red-900/20 border border-red-700/50 rounded-xl p-6">
          <div className="flex items-start gap-3">
            <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" />
            <div>
              <h3 className="text-lg font-semibold text-red-400">Error Loading Bots</h3>
              <p className="text-red-500/80 text-sm mt-1">
                {error instanceof Error ? error.message : 'Failed to load bots'}
              </p>
              <button
                onClick={() => refetch()}
                className="mt-4 px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors text-sm"
              >
                Try Again
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Bots Grid */}
      {!isLoading && !error && bots && bots.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {bots.map((bot) => (
            <BotCard
              key={bot.id}
              bot={mapBotForCard(bot)}
              onSelect={() => handleSelectBot(bot)}
              onStart={() => handleStartBot(bot.id)}
              onStop={() => handleStopBot(bot.id)}
              loading={startMutation.isPending || stopMutation.isPending}
            />
          ))}
        </div>
      )}

      {/* Empty State */}
      {!isLoading && !error && (!bots || bots.length === 0) && (
        <div className="bg-gray-800 rounded-xl p-12 text-center border border-gray-700">
          <div className="max-w-md mx-auto">
            <div className="w-16 h-16 bg-gray-700 rounded-full flex items-center justify-center mx-auto mb-4">
              <Bot className="w-8 h-8 text-gray-500" />
            </div>
            <h3 className="text-xl font-semibold text-white mb-2">No Trading Bots</h3>
            <p className="text-gray-400 mb-6">
              {statusFilter !== 'all'
                ? `No bots with status "${statusFilter}" found.`
                : 'Create your first trading bot to start automated trading with Atlas, Orion, or Nova strategies.'}
            </p>
            <button
              onClick={() => setShowCreateModal(true)}
              className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors inline-flex items-center gap-2"
            >
              <Plus className="w-4 h-4" />
              Create Your First Bot
            </button>
          </div>
        </div>
      )}

      {/* Create Bot Modal */}
      <CreateBotModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onSuccess={() => {
          refetch();
          setShowCreateModal(false);
        }}
      />
    </div>
  );
}

// ============================================================================
// Sub-components
// ============================================================================

interface StrategyInfoCardProps {
  icon: React.ReactNode;
  name: string;
  description: string;
  risk: string;
  color: 'blue' | 'purple' | 'orange';
}

function StrategyInfoCard({ icon, name, description, risk, color }: StrategyInfoCardProps) {
  const colorClasses = {
    blue: 'bg-blue-600/20 border-blue-700/50 text-blue-400',
    purple: 'bg-purple-600/20 border-purple-700/50 text-purple-400',
    orange: 'bg-orange-600/20 border-orange-700/50 text-orange-400',
  };

  const iconBgClasses = {
    blue: 'bg-blue-600',
    purple: 'bg-purple-600',
    orange: 'bg-orange-600',
  };

  const riskColors: Record<string, string> = {
    Low: 'text-green-400',
    Medium: 'text-yellow-400',
    High: 'text-red-400',
  };

  return (
    <div className={`p-4 rounded-lg border ${colorClasses[color]}`}>
      <div className="flex items-center gap-3">
        <div className={`p-2 rounded-lg ${iconBgClasses[color]}`}>
          <span className="text-white">{icon}</span>
        </div>
        <div>
          <h4 className="font-semibold text-white">{name}</h4>
          <p className="text-sm text-gray-400">{description}</p>
        </div>
        <div className="ml-auto">
          <span className={`text-xs font-medium ${riskColors[risk]}`}>{risk} Risk</span>
        </div>
      </div>
    </div>
  );
}
