/**
 * AgentsList Component
 * Displays a grid of trading bots (Atlas, Orion, Nova) with status filters
 */

import { useEffect, useState, useCallback } from 'react';
import { useAgentsStore } from '../../../../stores/agentsStore';
import { BotCard } from './BotCard';
import { Loader2, RefreshCw, AlertCircle, Bot } from 'lucide-react';
import type { BotStatus, TradingBot, TradingBotConfig } from '../../../../types/tradingAgents.types';

interface AgentsListProps {
  statusFilter?: BotStatus;
}

export function AgentsList({ statusFilter }: AgentsListProps) {
  const { bots, isLoading, error, fetchBots, selectBot, startBot, stopBot } = useAgentsStore();
  const [filterStatus, setFilterStatus] = useState<BotStatus | 'all'>('all');

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

  // Handler for starting a bot with default config
  const handleStartBot = useCallback(async (bot: TradingBot) => {
    const defaultConfig: TradingBotConfig = {
      initialEquity: 10000,
      riskPerTrade: 2.0,
      maxPositions: 3,
    };
    await startBot(bot.name, defaultConfig);
  }, [startBot]);

  // Handler for stopping a bot
  const handleStopBot = useCallback(async (bot: TradingBot) => {
    await stopBot(bot.name);
  }, [stopBot]);

  // Apply status filter
  const filteredBots = filterStatus === 'all'
    ? bots
    : bots.filter((bot) => bot.status === filterStatus);

  // Loading skeleton
  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-bold text-white">Trading Bots</h2>
          <button
            disabled
            className="flex items-center gap-2 px-4 py-2 bg-gray-700 text-gray-400 rounded-lg cursor-not-allowed"
          >
            <Loader2 className="w-4 h-4 animate-spin" />
            <span>Loading...</span>
          </button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {[1, 2, 3].map((i) => (
            <div key={i} className="bg-gray-800 rounded-xl p-6 border border-gray-700 animate-pulse">
              <div className="h-6 bg-gray-700 rounded w-1/2 mb-4"></div>
              <div className="h-4 bg-gray-700 rounded w-3/4 mb-6"></div>
              <div className="space-y-3">
                <div className="h-4 bg-gray-700 rounded w-full"></div>
                <div className="h-4 bg-gray-700 rounded w-full"></div>
                <div className="h-4 bg-gray-700 rounded w-2/3"></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-bold text-white">Trading Bots</h2>
          <button
            onClick={fetchBots}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
          >
            <RefreshCw className="w-4 h-4" />
            <span>Retry</span>
          </button>
        </div>

        <div className="bg-red-500/10 border border-red-500/30 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-500 mb-1">Error Loading Bots</h3>
              <p className="text-red-400 text-sm">{error}</p>
              <button
                onClick={fetchBots}
                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>
      </div>
    );
  }

  // Empty state
  if (filteredBots.length === 0) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-bold text-white">Trading Bots</h2>
          <button
            onClick={fetchBots}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
          >
            <RefreshCw className="w-4 h-4" />
            <span>Refresh</span>
          </button>
        </div>

        <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 Bots Available</h3>
            <p className="text-gray-400 mb-6">
              {filterStatus !== 'all'
                ? `No bots with status "${filterStatus}" found.`
                : 'Start configuring your trading bots to begin automated trading.'}
            </p>
            <button
              onClick={fetchBots}
              className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
            >
              Refresh List
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Main render
  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-white">Trading Bots</h2>
          <p className="text-gray-400 text-sm mt-1">
            {filteredBots.length} {filteredBots.length === 1 ? 'bot' : 'bots'} available
          </p>
        </div>
        <div className="flex items-center gap-3">
          {/* Status Filter */}
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(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="running">Running</option>
            <option value="paused">Paused</option>
            <option value="stopped">Stopped</option>
            <option value="idle">Idle</option>
            <option value="error">Error</option>
          </select>

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

      {/* Bots Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredBots.map((bot) => (
          <BotCard
            key={bot.id}
            bot={bot}
            onSelect={() => selectBot(bot.name)}
            onStart={() => handleStartBot(bot)}
            onStop={() => handleStopBot(bot)}
          />
        ))}
      </div>
    </div>
  );
}
