/**
 * Bot Detail Page
 * ===============
 * Detailed view of a trading bot with performance metrics, execution history,
 * and configuration management.
 */

import { useParams, useNavigate, Link } from 'react-router-dom';
import {
  ArrowLeft,
  Play,
  Square,
  Edit2,
  Trash2,
  RefreshCw,
  TrendingUp,
  TrendingDown,
  Activity,
  Clock,
  DollarSign,
  Target,
  AlertTriangle,
  CheckCircle2,
  XCircle,
  Loader2,
  Shield,
  Rocket,
} from 'lucide-react';
import { useBot, useBotPerformance, useBotExecutions, useStartBot, useStopBot, useDeleteBot } from '../hooks/useBots';
import type { TradingBot, BotExecution, BotPerformance, StrategyType } from '../../../services/bots.service';
import { useState } from 'react';

export default function BotDetailPage() {
  const { botId } = useParams<{ botId: string }>();
  const navigate = useNavigate();
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  const { data: bot, isLoading: botLoading, error: botError, refetch: refetchBot } = useBot(botId || '');
  const { data: performance, isLoading: perfLoading } = useBotPerformance(botId || '', !!bot);
  const { data: executions, isLoading: execLoading } = useBotExecutions(botId || '', { limit: 20 }, !!bot);

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

  const handleStart = async () => {
    if (!botId) return;
    try {
      await startMutation.mutateAsync(botId);
    } catch (error) {
      console.error('Failed to start bot:', error);
    }
  };

  const handleStop = async () => {
    if (!botId) return;
    try {
      await stopMutation.mutateAsync(botId);
    } catch (error) {
      console.error('Failed to stop bot:', error);
    }
  };

  const handleDelete = async () => {
    if (!botId) return;
    try {
      await deleteMutation.mutateAsync(botId);
      navigate('/trading/agents');
    } catch (error) {
      console.error('Failed to delete bot:', error);
    }
  };

  // Loading state
  if (botLoading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
      </div>
    );
  }

  // Error state
  if (botError || !bot) {
    return (
      <div className="space-y-6">
        <Link to="/trading/agents" className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors">
          <ArrowLeft className="w-4 h-4" />
          Back to Agents
        </Link>
        <div className="bg-red-900/20 border border-red-700/50 rounded-xl p-6 text-center">
          <AlertTriangle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <h2 className="text-xl font-bold text-red-400">Bot Not Found</h2>
          <p className="text-red-500/80 mt-2">The requested trading bot could not be found.</p>
          <Link
            to="/trading/agents"
            className="inline-block mt-4 px-6 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors"
          >
            Return to Agents
          </Link>
        </div>
      </div>
    );
  }

  const isActive = bot.status === 'active';
  const isPaused = bot.status === 'paused';
  const isStopped = bot.status === '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 className="flex items-center gap-4">
          <Link to="/trading/agents" className="text-gray-400 hover:text-white transition-colors">
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <div className="flex items-center gap-3">
            <StrategyIcon type={bot.strategyType || 'custom'} />
            <div>
              <h1 className="text-2xl font-bold text-white">{bot.name}</h1>
              <div className="flex items-center gap-2 mt-1">
                <StatusBadge status={bot.status} />
                <span className="text-gray-400 text-sm">{bot.strategyType || 'Custom'}</span>
              </div>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => refetchBot()}
            className="p-2 text-gray-400 hover:text-white transition-colors"
            title="Refresh"
          >
            <RefreshCw className="w-5 h-5" />
          </button>

          {(isStopped || isPaused) && (
            <button
              onClick={handleStart}
              disabled={startMutation.isPending}
              className="flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-700 text-white rounded-lg transition-colors"
            >
              {startMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
              Start
            </button>
          )}

          {isActive && (
            <button
              onClick={handleStop}
              disabled={stopMutation.isPending}
              className="flex items-center gap-2 px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-gray-700 text-white rounded-lg transition-colors"
            >
              {stopMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Square className="w-4 h-4" />}
              Stop
            </button>
          )}

          <button className="p-2 text-gray-400 hover:text-blue-400 transition-colors" title="Edit">
            <Edit2 className="w-5 h-5" />
          </button>

          <button
            onClick={() => setShowDeleteConfirm(true)}
            disabled={isActive}
            className="p-2 text-gray-400 hover:text-red-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            title={isActive ? 'Stop bot before deleting' : 'Delete'}
          >
            <Trash2 className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* Main Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Performance */}
        <div className="lg:col-span-2 space-y-6">
          {/* Key Metrics */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <MetricCard
              label="Total P&L"
              value={formatCurrency(bot.totalProfitLoss)}
              icon={<DollarSign className="w-5 h-5" />}
              trend={bot.totalProfitLoss >= 0 ? 'up' : 'down'}
            />
            <MetricCard
              label="Win Rate"
              value={`${bot.winRate.toFixed(1)}%`}
              icon={<Target className="w-5 h-5" />}
              trend={bot.winRate >= 50 ? 'up' : 'down'}
            />
            <MetricCard
              label="Total Trades"
              value={bot.totalTrades.toString()}
              icon={<Activity className="w-5 h-5" />}
            />
            <MetricCard
              label="Current Capital"
              value={formatCurrency(bot.currentCapital)}
              icon={<DollarSign className="w-5 h-5" />}
            />
          </div>

          {/* Performance Metrics */}
          <div className="bg-gray-800 rounded-xl p-6 border border-gray-700">
            <h3 className="text-lg font-semibold text-white mb-4">Performance Metrics</h3>
            {perfLoading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />
              </div>
            ) : performance ? (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <PerformanceItem label="Sharpe Ratio" value={performance.sharpeRatio.toFixed(2)} />
                <PerformanceItem label="Max Drawdown" value={`${performance.maxDrawdown.toFixed(1)}%`} />
                <PerformanceItem label="Profit Factor" value={performance.profitFactor.toFixed(2)} />
                <PerformanceItem label="Avg Win" value={formatCurrency(performance.averageWin)} />
                <PerformanceItem label="Avg Loss" value={formatCurrency(performance.averageLoss)} />
                <PerformanceItem label="Total Profit" value={formatCurrency(performance.profitLoss)} />
                <PerformanceItem label="Winning Trades" value={bot.winningTrades.toString()} />
                <PerformanceItem label="Losing Trades" value={(bot.totalTrades - bot.winningTrades).toString()} />
              </div>
            ) : (
              <p className="text-gray-400 text-center py-4">No performance data available</p>
            )}
          </div>

          {/* Execution History */}
          <div className="bg-gray-800 rounded-xl p-6 border border-gray-700">
            <h3 className="text-lg font-semibold text-white mb-4">Execution History</h3>
            {execLoading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />
              </div>
            ) : executions && executions.length > 0 ? (
              <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">Time</th>
                      <th className="pb-3 font-medium">Symbol</th>
                      <th className="pb-3 font-medium">Action</th>
                      <th className="pb-3 font-medium">Price</th>
                      <th className="pb-3 font-medium">Qty</th>
                      <th className="pb-3 font-medium">P&L</th>
                      <th className="pb-3 font-medium">Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {executions.map((exec) => (
                      <ExecutionRow key={exec.id} execution={exec} />
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-gray-400 text-center py-8">No executions yet</p>
            )}
          </div>
        </div>

        {/* Right Column - Configuration */}
        <div className="space-y-6">
          {/* Bot Configuration */}
          <div className="bg-gray-800 rounded-xl p-6 border border-gray-700">
            <h3 className="text-lg font-semibold text-white mb-4">Configuration</h3>
            <div className="space-y-4">
              <ConfigItem label="Symbols" value={bot.symbols.join(', ')} />
              <ConfigItem label="Timeframe" value={bot.timeframe.toUpperCase()} />
              <ConfigItem label="Initial Capital" value={formatCurrency(bot.initialCapital)} />
              <ConfigItem label="Max Position Size" value={`${bot.maxPositionSizePct}%`} />
              <ConfigItem label="Max Daily Loss" value={`${bot.maxDailyLossPct}%`} />
              <ConfigItem label="Max Drawdown" value={`${bot.maxDrawdownPct}%`} />
            </div>
          </div>

          {/* Status & Timestamps */}
          <div className="bg-gray-800 rounded-xl p-6 border border-gray-700">
            <h3 className="text-lg font-semibold text-white mb-4">Status</h3>
            <div className="space-y-4">
              <ConfigItem label="Created" value={formatDate(bot.createdAt)} />
              {bot.startedAt && <ConfigItem label="Started" value={formatDate(bot.startedAt)} />}
              {bot.stoppedAt && <ConfigItem label="Stopped" value={formatDate(bot.stoppedAt)} />}
              {bot.lastTradeAt && <ConfigItem label="Last Trade" value={formatDate(bot.lastTradeAt)} />}
            </div>
          </div>
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-gray-900 rounded-xl p-6 max-w-md w-full border border-gray-700">
            <h3 className="text-xl font-bold text-white mb-2">Delete Bot</h3>
            <p className="text-gray-400 mb-6">
              Are you sure you want to delete "{bot.name}"? This action cannot be undone.
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowDeleteConfirm(false)}
                className="flex-1 px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleDelete}
                disabled={deleteMutation.isPending}
                className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-gray-700 text-white rounded-lg transition-colors"
              >
                {deleteMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                Delete
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

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

function StrategyIcon({ type }: { type: StrategyType }) {
  const iconClass = 'w-6 h-6 text-white';
  const bgClass = {
    atlas: 'bg-blue-600',
    orion: 'bg-purple-600',
    nova: 'bg-orange-600',
    custom: 'bg-gray-600',
  }[type];

  return (
    <div className={`p-3 rounded-lg ${bgClass}`}>
      {type === 'atlas' && <Shield className={iconClass} />}
      {type === 'orion' && <Target className={iconClass} />}
      {type === 'nova' && <Rocket className={iconClass} />}
      {type === 'custom' && <Activity className={iconClass} />}
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const styles = {
    active: 'bg-green-900/50 text-green-400 border-green-700',
    paused: 'bg-yellow-900/50 text-yellow-400 border-yellow-700',
    stopped: 'bg-gray-900/50 text-gray-400 border-gray-700',
    error: 'bg-red-900/50 text-red-400 border-red-700',
  }[status] || 'bg-gray-900/50 text-gray-400 border-gray-700';

  return (
    <span className={`px-2.5 py-1 rounded-full text-xs font-semibold border ${styles}`}>
      {status.charAt(0).toUpperCase() + status.slice(1)}
    </span>
  );
}

interface MetricCardProps {
  label: string;
  value: string;
  icon: React.ReactNode;
  trend?: 'up' | 'down';
}

function MetricCard({ label, value, icon, trend }: MetricCardProps) {
  return (
    <div className="bg-gray-800 rounded-xl p-4 border border-gray-700">
      <div className="flex items-center justify-between mb-2">
        <span className="text-gray-400 text-sm">{label}</span>
        <span className="text-gray-500">{icon}</span>
      </div>
      <div className="flex items-center gap-2">
        <span className={`text-xl font-bold ${trend === 'up' ? 'text-green-400' : trend === 'down' ? 'text-red-400' : 'text-white'}`}>
          {value}
        </span>
        {trend === 'up' && <TrendingUp className="w-4 h-4 text-green-400" />}
        {trend === 'down' && <TrendingDown className="w-4 h-4 text-red-400" />}
      </div>
    </div>
  );
}

function PerformanceItem({ label, value }: { label: string; value: string }) {
  return (
    <div className="text-center p-3 bg-gray-900 rounded-lg">
      <span className="text-gray-500 text-xs block mb-1">{label}</span>
      <span className="text-white font-semibold">{value}</span>
    </div>
  );
}

function ConfigItem({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex justify-between items-center">
      <span className="text-gray-400 text-sm">{label}</span>
      <span className="text-white font-medium text-sm">{value}</span>
    </div>
  );
}

function ExecutionRow({ execution }: { execution: BotExecution }) {
  const isBuy = execution.action === 'buy';
  const isSuccess = execution.result === 'success';
  const isPnlPositive = (execution.pnl || 0) >= 0;

  return (
    <tr className="border-b border-gray-700/50 text-sm">
      <td className="py-3 text-gray-300">
        <div className="flex items-center gap-1">
          <Clock className="w-3 h-3 text-gray-500" />
          {formatTime(execution.timestamp)}
        </div>
      </td>
      <td className="py-3 text-white font-medium">{execution.symbol}</td>
      <td className="py-3">
        <span className={`px-2 py-0.5 rounded text-xs font-semibold ${isBuy ? 'bg-green-900/50 text-green-400' : 'bg-red-900/50 text-red-400'}`}>
          {execution.action.toUpperCase()}
        </span>
      </td>
      <td className="py-3 text-gray-300">{formatCurrency(execution.price)}</td>
      <td className="py-3 text-gray-300">{execution.quantity.toFixed(4)}</td>
      <td className={`py-3 font-medium ${isPnlPositive ? 'text-green-400' : 'text-red-400'}`}>
        {execution.pnl !== undefined ? formatCurrency(execution.pnl) : '-'}
      </td>
      <td className="py-3">
        {isSuccess ? (
          <CheckCircle2 className="w-4 h-4 text-green-400" />
        ) : execution.result === 'failed' ? (
          <XCircle className="w-4 h-4 text-red-400" />
        ) : (
          <Loader2 className="w-4 h-4 text-yellow-400 animate-spin" />
        )}
      </td>
    </tr>
  );
}

// ============================================================================
// Helpers
// ============================================================================

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

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

function formatTime(dateStr: string): string {
  return new Date(dateStr).toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}
