/**
 * MT4LiveTradesPanel Component
 * Real-time positions dashboard with live P&L updates via WebSocket
 */

import React, { useState, useMemo } from 'react';
import {
  TrendingUp,
  TrendingDown,
  X,
  Edit3,
  RefreshCw,
  AlertTriangle,
  DollarSign,
  Percent,
  Activity,
  ChevronDown,
  ChevronUp,
  Filter,
  MoreVertical,
} from 'lucide-react';
import { useMT4WebSocket, MT4Position } from '../hooks/useMT4WebSocket';
import { closeMT4Position } from '../../../services/trading.service';

interface MT4LiveTradesPanelProps {
  onModifyPosition?: (position: MT4Position) => void;
  onClosePosition?: (ticket: number) => void;
  onPositionSelect?: (position: MT4Position) => void;
  autoRefresh?: boolean;
  compact?: boolean;
}

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

const MT4LiveTradesPanel: React.FC<MT4LiveTradesPanelProps> = ({
  onModifyPosition,
  onClosePosition,
  onPositionSelect,
  autoRefresh = true,
  compact = false,
}) => {
  const { connected, positions, account, error } = useMT4WebSocket({
    autoConnect: autoRefresh,
  });

  const [sortField, setSortField] = useState<SortField>('openTime');
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
  const [filterType, setFilterType] = useState<FilterType>('all');
  const [expandedTicket, setExpandedTicket] = useState<number | null>(null);
  const [closingTicket, setClosingTicket] = useState<number | null>(null);
  const [showCloseAllConfirm, setShowCloseAllConfirm] = useState(false);

  // Calculate aggregate metrics
  const metrics = useMemo(() => {
    const totalProfit = positions.reduce((sum, p) => sum + p.profit, 0);
    const totalSwap = positions.reduce((sum, p) => sum + p.swap, 0);
    const totalCommission = positions.reduce((sum, p) => sum + p.commission, 0);
    const winningCount = positions.filter((p) => p.profit > 0).length;
    const losingCount = positions.filter((p) => p.profit < 0).length;
    const totalLots = positions.reduce((sum, p) => sum + p.lots, 0);

    return {
      totalProfit,
      totalSwap,
      totalCommission,
      netProfit: totalProfit + totalSwap - totalCommission,
      winningCount,
      losingCount,
      totalLots,
      marginLevel: account?.marginLevel || 0,
    };
  }, [positions, account]);

  // Filter and sort positions
  const filteredPositions = useMemo(() => {
    let result = [...positions];

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

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

    return result;
  }, [positions, filterType, sortField, sortDirection]);

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

  const handleClosePosition = async (ticket: number) => {
    setClosingTicket(ticket);
    try {
      await closeMT4Position(ticket);
      onClosePosition?.(ticket);
    } catch (err) {
      console.error('Failed to close position:', err);
    } finally {
      setClosingTicket(null);
    }
  };

  const handleCloseAll = async () => {
    setShowCloseAllConfirm(false);
    for (const position of positions) {
      await handleClosePosition(position.ticket);
    }
  };

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

  const getMarginLevelColor = (level: number) => {
    if (level >= 200) return 'text-green-400';
    if (level >= 100) return 'text-yellow-400';
    return 'text-red-400';
  };

  const getProfitColor = (profit: number) => {
    if (profit > 0) return 'text-green-400';
    if (profit < 0) return 'text-red-400';
    return 'text-gray-400';
  };

  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-3">
          <div className={`p-2 rounded-lg ${connected ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
            <Activity className={`w-5 h-5 ${connected ? 'text-green-400' : 'text-red-400'}`} />
          </div>
          <div>
            <h3 className="font-semibold text-white">Live Positions</h3>
            <p className="text-xs text-gray-500">
              {positions.length} open • {connected ? 'Connected' : 'Disconnected'}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {/* Filter */}
          <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-xs text-white"
          >
            <option value="all">All</option>
            <option value="profitable">Winning</option>
            <option value="losing">Losing</option>
          </select>

          {/* Close All Button */}
          {positions.length > 0 && (
            <button
              onClick={() => setShowCloseAllConfirm(true)}
              className="px-3 py-1 bg-red-600/20 hover:bg-red-600/30 text-red-400 rounded text-xs font-medium transition-colors"
            >
              Close All
            </button>
          )}
        </div>
      </div>

      {/* Summary Metrics */}
      <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 ${getProfitColor(metrics.netProfit)}`}>
            {metrics.netProfit >= 0 ? '+' : ''}{metrics.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">
            <span className="text-green-400">{metrics.winningCount}</span>
            <span className="text-gray-600">/</span>
            <span className="text-red-400">{metrics.losingCount}</span>
          </div>
          <div className="text-xs text-gray-500">Win/Lose</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="text-lg font-bold text-white">{metrics.totalLots.toFixed(2)}</div>
          <div className="text-xs text-gray-500">Total Lots</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className={`text-lg font-bold ${getMarginLevelColor(metrics.marginLevel)}`}>
            {metrics.marginLevel.toFixed(0)}%
          </div>
          <div className="text-xs text-gray-500">Margin Level</div>
        </div>
      </div>

      {/* Positions List */}
      {error ? (
        <div className="text-center py-8">
          <AlertTriangle className="w-10 h-10 text-red-400 mx-auto mb-2" />
          <p className="text-gray-400">{error}</p>
        </div>
      ) : filteredPositions.length === 0 ? (
        <div className="text-center py-8">
          <Activity className="w-10 h-10 text-gray-600 mx-auto mb-2" />
          <p className="text-gray-400">No open positions</p>
        </div>
      ) : (
        <div className="space-y-2 max-h-[400px] overflow-y-auto">
          {filteredPositions.map((position) => (
            <div
              key={position.ticket}
              className={`bg-gray-900/50 rounded-lg border transition-all ${
                expandedTicket === position.ticket
                  ? 'border-blue-500/50'
                  : 'border-gray-700/50 hover:border-gray-600'
              }`}
            >
              {/* Main Row */}
              <div
                onClick={() => {
                  setExpandedTicket(expandedTicket === position.ticket ? null : position.ticket);
                  onPositionSelect?.(position);
                }}
                className="flex items-center justify-between p-3 cursor-pointer"
              >
                <div className="flex items-center gap-3">
                  <div className={`p-1.5 rounded ${position.type === 'BUY' ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
                    {position.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">{position.symbol}</span>
                      <span className="text-xs text-gray-500">{position.lots} lots</span>
                    </div>
                    <div className="text-xs text-gray-500">
                      #{position.ticket} • {formatTime(position.openTime)}
                    </div>
                  </div>
                </div>

                <div className="flex items-center gap-3">
                  <div className="text-right">
                    <div className={`font-mono font-medium ${getProfitColor(position.profit)}`}>
                      {position.profit >= 0 ? '+' : ''}{position.profit.toFixed(2)}
                    </div>
                    <div className="text-xs text-gray-500">
                      {position.openPrice.toFixed(5)} → {position.currentPrice.toFixed(5)}
                    </div>
                  </div>
                  {expandedTicket === position.ticket ? (
                    <ChevronUp className="w-4 h-4 text-gray-500" />
                  ) : (
                    <ChevronDown className="w-4 h-4 text-gray-500" />
                  )}
                </div>
              </div>

              {/* Expanded Details */}
              {expandedTicket === position.ticket && (
                <div className="px-3 pb-3 pt-1 border-t border-gray-700/50">
                  <div className="grid grid-cols-4 gap-3 text-xs mb-3">
                    <div>
                      <span className="text-gray-500">Entry:</span>
                      <span className="text-white ml-1 font-mono">{position.openPrice.toFixed(5)}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">Current:</span>
                      <span className="text-white ml-1 font-mono">{position.currentPrice.toFixed(5)}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">SL:</span>
                      <span className={`ml-1 font-mono ${position.stopLoss ? 'text-red-400' : 'text-gray-600'}`}>
                        {position.stopLoss?.toFixed(5) || 'None'}
                      </span>
                    </div>
                    <div>
                      <span className="text-gray-500">TP:</span>
                      <span className={`ml-1 font-mono ${position.takeProfit ? 'text-green-400' : 'text-gray-600'}`}>
                        {position.takeProfit?.toFixed(5) || 'None'}
                      </span>
                    </div>
                  </div>

                  <div className="flex items-center justify-between">
                    <div className="text-xs text-gray-500">
                      Swap: <span className="text-gray-400">{position.swap.toFixed(2)}</span>
                      {' • '}
                      Comm: <span className="text-gray-400">{position.commission.toFixed(2)}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      {onModifyPosition && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            onModifyPosition(position);
                          }}
                          className="flex items-center gap-1 px-2 py-1 text-xs text-blue-400 hover:bg-blue-500/10 rounded transition-colors"
                        >
                          <Edit3 className="w-3 h-3" />
                          Modify
                        </button>
                      )}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleClosePosition(position.ticket);
                        }}
                        disabled={closingTicket === position.ticket}
                        className="flex items-center gap-1 px-2 py-1 text-xs text-red-400 hover:bg-red-500/10 rounded transition-colors disabled:opacity-50"
                      >
                        <X className="w-3 h-3" />
                        {closingTicket === position.ticket ? 'Closing...' : 'Close'}
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Close All Confirmation Modal */}
      {showCloseAllConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70">
          <div className="w-full max-w-sm bg-gray-800 rounded-xl p-6">
            <div className="text-center">
              <AlertTriangle className="w-12 h-12 text-red-400 mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-white mb-2">Close All Positions?</h3>
              <p className="text-gray-400 text-sm mb-4">
                This will close {positions.length} positions with a net P&L of{' '}
                <span className={getProfitColor(metrics.netProfit)}>
                  {metrics.netProfit >= 0 ? '+' : ''}{metrics.netProfit.toFixed(2)}
                </span>
              </p>
              <div className="flex items-center gap-3">
                <button
                  onClick={() => setShowCloseAllConfirm(false)}
                  className="flex-1 py-2.5 bg-gray-700 hover:bg-gray-600 text-white rounded-lg font-medium"
                >
                  Cancel
                </button>
                <button
                  onClick={handleCloseAll}
                  className="flex-1 py-2.5 bg-red-600 hover:bg-red-500 text-white rounded-lg font-medium"
                >
                  Close All
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MT4LiveTradesPanel;
