/**
 * TradeExecutionHistory Component
 * Display session/daily trade history with performance stats
 */

import React, { useState, useEffect } from 'react';
import {
  History,
  TrendingUp,
  TrendingDown,
  Clock,
  DollarSign,
  Target,
  XCircle,
  Download,
  RefreshCw,
  Loader2,
  ChevronDown,
  ChevronUp,
  Filter,
} from 'lucide-react';

interface HistoricalTrade {
  ticket: number;
  symbol: string;
  type: 'BUY' | 'SELL';
  lots: number;
  openPrice: number;
  closePrice: number;
  openTime: string;
  closeTime: string;
  profit: number;
  commission: number;
  swap: number;
  stopLoss?: number;
  takeProfit?: number;
  closedBy: 'manual' | 'sl' | 'tp' | 'margin_call';
}

interface TradeExecutionHistoryProps {
  trades?: HistoricalTrade[];
  onRefresh?: () => Promise<HistoricalTrade[]>;
  maxItems?: number;
  showExport?: boolean;
  compact?: boolean;
}

type SortField = 'closeTime' | 'profit' | 'symbol';
type SortDirection = 'asc' | 'desc';
type FilterType = 'all' | 'profitable' | 'losing';

const TradeExecutionHistory: React.FC<TradeExecutionHistoryProps> = ({
  trades: initialTrades = [],
  onRefresh,
  maxItems = 50,
  showExport = true,
  compact = false,
}) => {
  const [trades, setTrades] = useState<HistoricalTrade[]>(initialTrades);
  const [loading, setLoading] = useState(false);
  const [sortField, setSortField] = useState<SortField>('closeTime');
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
  const [filterType, setFilterType] = useState<FilterType>('all');
  const [expandedTrade, setExpandedTrade] = useState<number | null>(null);

  useEffect(() => {
    setTrades(initialTrades);
  }, [initialTrades]);

  const handleRefresh = async () => {
    if (!onRefresh) return;
    setLoading(true);
    try {
      const newTrades = await onRefresh();
      setTrades(newTrades);
    } catch (err) {
      console.error('Failed to refresh trades:', err);
    } finally {
      setLoading(false);
    }
  };

  // Calculate summary stats
  const stats = React.useMemo(() => {
    const winning = trades.filter((t) => t.profit > 0);
    const losing = trades.filter((t) => t.profit < 0);
    const totalProfit = trades.reduce((sum, t) => sum + t.profit, 0);
    const totalCommission = trades.reduce((sum, t) => sum + t.commission, 0);
    const totalSwap = trades.reduce((sum, t) => sum + t.swap, 0);
    const netProfit = totalProfit - totalCommission + totalSwap;
    const winRate = trades.length > 0 ? (winning.length / trades.length) * 100 : 0;
    const avgWin = winning.length > 0
      ? winning.reduce((sum, t) => sum + t.profit, 0) / winning.length
      : 0;
    const avgLoss = losing.length > 0
      ? Math.abs(losing.reduce((sum, t) => sum + t.profit, 0) / losing.length)
      : 0;
    const profitFactor = avgLoss > 0 ? avgWin / avgLoss : avgWin > 0 ? Infinity : 0;

    return {
      totalTrades: trades.length,
      winning: winning.length,
      losing: losing.length,
      breakeven: trades.length - winning.length - losing.length,
      totalProfit,
      netProfit,
      totalCommission,
      totalSwap,
      winRate,
      avgWin,
      avgLoss,
      profitFactor,
      bestTrade: trades.length > 0 ? Math.max(...trades.map((t) => t.profit)) : 0,
      worstTrade: trades.length > 0 ? Math.min(...trades.map((t) => t.profit)) : 0,
    };
  }, [trades]);

  // Filter and sort trades
  const filteredTrades = React.useMemo(() => {
    let result = [...trades];

    // Apply filter
    if (filterType === 'profitable') {
      result = result.filter((t) => t.profit > 0);
    } else if (filterType === 'losing') {
      result = result.filter((t) => t.profit < 0);
    }

    // Apply sort
    result.sort((a, b) => {
      let comparison = 0;
      switch (sortField) {
        case 'closeTime':
          comparison = new Date(a.closeTime).getTime() - new Date(b.closeTime).getTime();
          break;
        case 'profit':
          comparison = a.profit - b.profit;
          break;
        case 'symbol':
          comparison = a.symbol.localeCompare(b.symbol);
          break;
      }
      return sortDirection === 'asc' ? comparison : -comparison;
    });

    return result.slice(0, maxItems);
  }, [trades, filterType, sortField, sortDirection, maxItems]);

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('desc');
    }
  };

  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  };

  const getCloseReasonIcon = (closedBy: HistoricalTrade['closedBy']) => {
    switch (closedBy) {
      case 'tp':
        return <Target className="w-3 h-3 text-green-400" aria-label="Take Profit" />;
      case 'sl':
        return <XCircle className="w-3 h-3 text-red-400" aria-label="Stop Loss" />;
      case 'margin_call':
        return <XCircle className="w-3 h-3 text-orange-400" aria-label="Margin Call" />;
      default:
        return <Clock className="w-3 h-3 text-gray-400" aria-label="Manual Close" />;
    }
  };

  const handleExport = () => {
    const headers = ['Ticket', 'Symbol', 'Type', 'Lots', 'Open Price', 'Close Price', 'Open Time', 'Close Time', 'Profit', 'Commission', 'Swap', 'Closed By'];
    const rows = trades.map((t) => [
      t.ticket,
      t.symbol,
      t.type,
      t.lots,
      t.openPrice,
      t.closePrice,
      t.openTime,
      t.closeTime,
      t.profit.toFixed(2),
      t.commission.toFixed(2),
      t.swap.toFixed(2),
      t.closedBy,
    ]);

    const csv = [headers, ...rows].map((row) => row.join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `trade-history-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <History className="w-5 h-5 text-blue-400" />
          <h3 className="font-semibold text-white">Trade History</h3>
          <span className="text-sm text-gray-500">({trades.length})</span>
        </div>
        <div className="flex items-center gap-2">
          {onRefresh && (
            <button
              onClick={handleRefresh}
              disabled={loading}
              className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            </button>
          )}
          {showExport && trades.length > 0 && (
            <button
              onClick={handleExport}
              className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
            >
              <Download className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* Summary Stats */}
      {!compact && trades.length > 0 && (
        <div className="grid grid-cols-4 gap-3 mb-4">
          <div className="p-3 bg-gray-900/50 rounded-lg text-center">
            <div className={`text-lg font-bold ${stats.netProfit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
              {stats.netProfit >= 0 ? '+' : ''}{stats.netProfit.toFixed(2)}
            </div>
            <div className="text-xs text-gray-500">Net P&L</div>
          </div>
          <div className="p-3 bg-gray-900/50 rounded-lg text-center">
            <div className="text-lg font-bold text-white">{stats.winRate.toFixed(1)}%</div>
            <div className="text-xs text-gray-500">Win Rate</div>
          </div>
          <div className="p-3 bg-gray-900/50 rounded-lg text-center">
            <div className="text-lg font-bold text-white">
              {stats.profitFactor === Infinity ? '∞' : stats.profitFactor.toFixed(2)}
            </div>
            <div className="text-xs text-gray-500">Profit Factor</div>
          </div>
          <div className="p-3 bg-gray-900/50 rounded-lg text-center">
            <div className="text-lg font-bold text-white">
              <span className="text-green-400">{stats.winning}</span>
              <span className="text-gray-500">/</span>
              <span className="text-red-400">{stats.losing}</span>
            </div>
            <div className="text-xs text-gray-500">W/L</div>
          </div>
        </div>
      )}

      {/* Filter & Sort */}
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-2">
          <Filter className="w-4 h-4 text-gray-500" />
          <select
            value={filterType}
            onChange={(e) => setFilterType(e.target.value as FilterType)}
            className="px-2 py-1 bg-gray-900 border border-gray-700 rounded text-sm text-white"
          >
            <option value="all">All Trades</option>
            <option value="profitable">Profitable</option>
            <option value="losing">Losing</option>
          </select>
        </div>
        <div className="flex items-center gap-1 text-xs text-gray-500">
          Sort:
          <button
            onClick={() => handleSort('closeTime')}
            className={`px-2 py-1 rounded ${sortField === 'closeTime' ? 'bg-gray-700 text-white' : 'hover:bg-gray-700'}`}
          >
            Time
          </button>
          <button
            onClick={() => handleSort('profit')}
            className={`px-2 py-1 rounded ${sortField === 'profit' ? 'bg-gray-700 text-white' : 'hover:bg-gray-700'}`}
          >
            P&L
          </button>
        </div>
      </div>

      {/* Trade List */}
      {loading && trades.length === 0 ? (
        <div className="flex items-center justify-center py-8">
          <Loader2 className="w-6 h-6 text-blue-400 animate-spin" />
        </div>
      ) : filteredTrades.length === 0 ? (
        <div className="text-center py-8">
          <History className="w-10 h-10 text-gray-600 mx-auto mb-2" />
          <p className="text-gray-500 text-sm">No trades yet</p>
        </div>
      ) : (
        <div className="space-y-2 max-h-[400px] overflow-y-auto">
          {filteredTrades.map((trade) => (
            <div
              key={trade.ticket}
              className="bg-gray-900/50 rounded-lg border border-gray-700/50 overflow-hidden"
            >
              <div
                onClick={() => setExpandedTrade(expandedTrade === trade.ticket ? null : trade.ticket)}
                className="flex items-center justify-between p-3 cursor-pointer hover:bg-gray-800/50 transition-colors"
              >
                <div className="flex items-center gap-3">
                  <div className={`p-1.5 rounded ${trade.type === 'BUY' ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
                    {trade.type === 'BUY' ? (
                      <TrendingUp className="w-4 h-4 text-green-400" />
                    ) : (
                      <TrendingDown className="w-4 h-4 text-red-400" />
                    )}
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-white">{trade.symbol}</span>
                      <span className="text-xs text-gray-500">{trade.lots} lots</span>
                      {getCloseReasonIcon(trade.closedBy)}
                    </div>
                    <div className="text-xs text-gray-500">
                      {formatDate(trade.closeTime)} {formatTime(trade.closeTime)}
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <div className={`text-right font-mono font-medium ${trade.profit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                    {trade.profit >= 0 ? '+' : ''}{trade.profit.toFixed(2)}
                  </div>
                  {expandedTrade === trade.ticket ? (
                    <ChevronUp className="w-4 h-4 text-gray-500" />
                  ) : (
                    <ChevronDown className="w-4 h-4 text-gray-500" />
                  )}
                </div>
              </div>

              {/* Expanded Details */}
              {expandedTrade === trade.ticket && (
                <div className="px-3 pb-3 pt-1 border-t border-gray-700/50">
                  <div className="grid grid-cols-3 gap-3 text-xs">
                    <div>
                      <div className="text-gray-500">Entry</div>
                      <div className="text-white font-mono">{trade.openPrice.toFixed(5)}</div>
                      <div className="text-gray-600">{formatTime(trade.openTime)}</div>
                    </div>
                    <div>
                      <div className="text-gray-500">Exit</div>
                      <div className="text-white font-mono">{trade.closePrice.toFixed(5)}</div>
                      <div className="text-gray-600">{formatTime(trade.closeTime)}</div>
                    </div>
                    <div>
                      <div className="text-gray-500">Fees</div>
                      <div className="text-gray-400 font-mono">
                        {(trade.commission + trade.swap).toFixed(2)}
                      </div>
                      <div className="text-gray-600">
                        C: {trade.commission.toFixed(2)} / S: {trade.swap.toFixed(2)}
                      </div>
                    </div>
                  </div>
                  {(trade.stopLoss || trade.takeProfit) && (
                    <div className="flex gap-4 mt-2 pt-2 border-t border-gray-700/50 text-xs">
                      {trade.stopLoss && (
                        <div>
                          <span className="text-gray-500">SL:</span>{' '}
                          <span className="text-red-400 font-mono">{trade.stopLoss.toFixed(5)}</span>
                        </div>
                      )}
                      {trade.takeProfit && (
                        <div>
                          <span className="text-gray-500">TP:</span>{' '}
                          <span className="text-green-400 font-mono">{trade.takeProfit.toFixed(5)}</span>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default TradeExecutionHistory;
