/**
 * SignalPerformanceTracker Component
 * Signal history and performance analysis
 * OQI-006: Senales ML
 */

import React, { useState, useMemo } from 'react';
import {
  History,
  TrendingUp,
  TrendingDown,
  Target,
  Shield,
  Clock,
  Filter,
  Search,
  ChevronDown,
  ChevronUp,
  CheckCircle,
  XCircle,
  AlertCircle,
  DollarSign,
  Percent,
  Calendar,
  BarChart3,
  Download,
} from 'lucide-react';

export type SignalStatus = 'active' | 'executed' | 'tp_hit' | 'sl_hit' | 'expired' | 'cancelled';

export interface SignalHistoryEntry {
  id: string;
  symbol: string;
  direction: 'BUY' | 'SELL';
  confidence: number;
  entryPrice: number;
  currentPrice?: number;
  stopLoss: number;
  takeProfit: number;
  status: SignalStatus;
  createdAt: string;
  executedAt?: string;
  closedAt?: string;
  actualProfit?: number;
  actualProfitPercent?: number;
  expectedRR: number;
  actualRR?: number;
  modelName: string;
  reasoning?: string;
}

interface SignalStats {
  totalSignals: number;
  executed: number;
  tpHit: number;
  slHit: number;
  expired: number;
  winRate: number;
  totalProfit: number;
  avgProfit: number;
  avgRR: number;
  profitFactor: number;
}

interface SignalPerformanceTrackerProps {
  signals: SignalHistoryEntry[];
  onSignalSelect?: (signal: SignalHistoryEntry) => void;
  onExport?: () => void;
  maxItems?: number;
  compact?: boolean;
}

const SignalPerformanceTracker: React.FC<SignalPerformanceTrackerProps> = ({
  signals,
  onSignalSelect,
  onExport,
  maxItems = 50,
  compact = false,
}) => {
  const [filterSymbol, setFilterSymbol] = useState('');
  const [filterStatus, setFilterStatus] = useState<SignalStatus | 'all'>('all');
  const [filterDirection, setFilterDirection] = useState<'BUY' | 'SELL' | 'all'>('all');
  const [sortBy, setSortBy] = useState<'date' | 'profit' | 'confidence'>('date');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');
  const [expandedId, setExpandedId] = useState<string | null>(null);

  // Calculate stats
  const stats: SignalStats = useMemo(() => {
    const executed = signals.filter((s) => s.status !== 'active' && s.status !== 'cancelled');
    const winners = signals.filter((s) => s.status === 'tp_hit');
    const losers = signals.filter((s) => s.status === 'sl_hit');

    const totalProfit = executed.reduce((sum, s) => sum + (s.actualProfit || 0), 0);
    const totalWins = winners.reduce((sum, s) => sum + (s.actualProfit || 0), 0);
    const totalLosses = Math.abs(losers.reduce((sum, s) => sum + (s.actualProfit || 0), 0));

    return {
      totalSignals: signals.length,
      executed: executed.length,
      tpHit: winners.length,
      slHit: losers.length,
      expired: signals.filter((s) => s.status === 'expired').length,
      winRate: executed.length > 0 ? (winners.length / executed.length) * 100 : 0,
      totalProfit,
      avgProfit: executed.length > 0 ? totalProfit / executed.length : 0,
      avgRR: executed.filter((s) => s.actualRR).reduce((sum, s) => sum + (s.actualRR || 0), 0) / (executed.filter((s) => s.actualRR).length || 1),
      profitFactor: totalLosses > 0 ? totalWins / totalLosses : totalWins,
    };
  }, [signals]);

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

    if (filterSymbol) {
      result = result.filter((s) => s.symbol.toLowerCase().includes(filterSymbol.toLowerCase()));
    }
    if (filterStatus !== 'all') {
      result = result.filter((s) => s.status === filterStatus);
    }
    if (filterDirection !== 'all') {
      result = result.filter((s) => s.direction === filterDirection);
    }

    result.sort((a, b) => {
      let comparison = 0;
      switch (sortBy) {
        case 'date':
          comparison = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
          break;
        case 'profit':
          comparison = (b.actualProfit || 0) - (a.actualProfit || 0);
          break;
        case 'confidence':
          comparison = b.confidence - a.confidence;
          break;
      }
      return sortDir === 'desc' ? comparison : -comparison;
    });

    return result.slice(0, maxItems);
  }, [signals, filterSymbol, filterStatus, filterDirection, sortBy, sortDir, maxItems]);

  const getStatusIcon = (status: SignalStatus) => {
    switch (status) {
      case 'tp_hit':
        return <CheckCircle className="w-4 h-4 text-green-400" />;
      case 'sl_hit':
        return <XCircle className="w-4 h-4 text-red-400" />;
      case 'expired':
        return <Clock className="w-4 h-4 text-gray-400" />;
      case 'active':
        return <AlertCircle className="w-4 h-4 text-blue-400" />;
      case 'executed':
        return <Target className="w-4 h-4 text-yellow-400" />;
      default:
        return <AlertCircle className="w-4 h-4 text-gray-400" />;
    }
  };

  const getStatusLabel = (status: SignalStatus) => {
    switch (status) {
      case 'tp_hit':
        return 'TP Hit';
      case 'sl_hit':
        return 'SL Hit';
      case 'expired':
        return 'Expired';
      case 'active':
        return 'Active';
      case 'executed':
        return 'Running';
      case 'cancelled':
        return 'Cancelled';
      default:
        return status;
    }
  };

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

  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 bg-purple-500/20 rounded-lg">
            <History className="w-5 h-5 text-purple-400" />
          </div>
          <div>
            <h3 className="font-semibold text-white">Signal Performance</h3>
            <p className="text-xs text-gray-500">{stats.totalSignals} signals tracked</p>
          </div>
        </div>
        {onExport && (
          <button
            onClick={onExport}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
          >
            <Download className="w-4 h-4" />
          </button>
        )}
      </div>

      {/* Stats Grid */}
      <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 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 ${stats.totalProfit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            ${stats.totalProfit.toFixed(2)}
          </div>
          <div className="text-xs text-gray-500">Total 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.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.tpHit}</span>
            <span className="text-gray-600">/</span>
            <span className="text-red-400">{stats.slHit}</span>
          </div>
          <div className="text-xs text-gray-500">TP/SL Hits</div>
        </div>
      </div>

      {/* Filters */}
      {!compact && (
        <div className="flex flex-wrap items-center gap-2 mb-4">
          <div className="relative flex-1 min-w-[150px]">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
            <input
              type="text"
              value={filterSymbol}
              onChange={(e) => setFilterSymbol(e.target.value)}
              placeholder="Filter symbol..."
              className="w-full pl-10 pr-3 py-1.5 bg-gray-900 border border-gray-700 rounded text-sm text-white focus:outline-none focus:border-blue-500"
            />
          </div>
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value as SignalStatus | 'all')}
            className="px-3 py-1.5 bg-gray-900 border border-gray-700 rounded text-sm text-white"
          >
            <option value="all">All Status</option>
            <option value="tp_hit">TP Hit</option>
            <option value="sl_hit">SL Hit</option>
            <option value="active">Active</option>
            <option value="expired">Expired</option>
          </select>
          <select
            value={filterDirection}
            onChange={(e) => setFilterDirection(e.target.value as 'BUY' | 'SELL' | 'all')}
            className="px-3 py-1.5 bg-gray-900 border border-gray-700 rounded text-sm text-white"
          >
            <option value="all">All Directions</option>
            <option value="BUY">Buy Only</option>
            <option value="SELL">Sell Only</option>
          </select>
          <select
            value={`${sortBy}-${sortDir}`}
            onChange={(e) => {
              const [field, dir] = e.target.value.split('-');
              setSortBy(field as 'date' | 'profit' | 'confidence');
              setSortDir(dir as 'asc' | 'desc');
            }}
            className="px-3 py-1.5 bg-gray-900 border border-gray-700 rounded text-sm text-white"
          >
            <option value="date-desc">Newest First</option>
            <option value="date-asc">Oldest First</option>
            <option value="profit-desc">Highest Profit</option>
            <option value="profit-asc">Lowest Profit</option>
            <option value="confidence-desc">Highest Confidence</option>
          </select>
        </div>
      )}

      {/* Signals List */}
      {filteredSignals.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-400">No signals found</p>
        </div>
      ) : (
        <div className="space-y-2 max-h-[400px] overflow-y-auto">
          {filteredSignals.map((signal) => {
            const isExpanded = expandedId === signal.id;

            return (
              <div
                key={signal.id}
                onClick={() => {
                  setExpandedId(isExpanded ? null : signal.id);
                  onSignalSelect?.(signal);
                }}
                className={`p-3 bg-gray-900/50 rounded-lg border cursor-pointer transition-all ${
                  isExpanded ? 'border-blue-500/50' : 'border-gray-700/50 hover:border-gray-600'
                }`}
              >
                {/* Main Row */}
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className={`p-1.5 rounded ${signal.direction === 'BUY' ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
                      {signal.direction === '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">{signal.symbol}</span>
                        <span className={`px-2 py-0.5 rounded text-xs ${
                          signal.status === 'tp_hit'
                            ? 'bg-green-500/20 text-green-400'
                            : signal.status === 'sl_hit'
                            ? 'bg-red-500/20 text-red-400'
                            : signal.status === 'active'
                            ? 'bg-blue-500/20 text-blue-400'
                            : 'bg-gray-500/20 text-gray-400'
                        }`}>
                          {getStatusLabel(signal.status)}
                        </span>
                      </div>
                      <div className="text-xs text-gray-500">
                        {formatDate(signal.createdAt)} • {signal.modelName}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-3">
                    <div className="text-right">
                      {signal.actualProfit !== undefined ? (
                        <div className={`font-mono font-medium ${signal.actualProfit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                          {signal.actualProfit >= 0 ? '+' : ''}${signal.actualProfit.toFixed(2)}
                        </div>
                      ) : (
                        <div className="font-mono text-gray-400">--</div>
                      )}
                      <div className="text-xs text-gray-500">
                        Conf: {signal.confidence.toFixed(0)}%
                      </div>
                    </div>
                    {isExpanded ? (
                      <ChevronUp className="w-4 h-4 text-gray-500" />
                    ) : (
                      <ChevronDown className="w-4 h-4 text-gray-500" />
                    )}
                  </div>
                </div>

                {/* Expanded Details */}
                {isExpanded && (
                  <div className="mt-3 pt-3 border-t border-gray-700/50">
                    <div className="grid grid-cols-3 gap-3 text-xs mb-3">
                      <div>
                        <span className="text-gray-500">Entry:</span>
                        <span className="text-white ml-2 font-mono">{signal.entryPrice.toFixed(5)}</span>
                      </div>
                      <div>
                        <span className="text-gray-500">SL:</span>
                        <span className="text-red-400 ml-2 font-mono">{signal.stopLoss.toFixed(5)}</span>
                      </div>
                      <div>
                        <span className="text-gray-500">TP:</span>
                        <span className="text-green-400 ml-2 font-mono">{signal.takeProfit.toFixed(5)}</span>
                      </div>
                    </div>

                    <div className="flex items-center gap-4 text-xs">
                      <div>
                        <span className="text-gray-500">Expected RR:</span>
                        <span className="text-white ml-2">1:{signal.expectedRR.toFixed(2)}</span>
                      </div>
                      {signal.actualRR && (
                        <div>
                          <span className="text-gray-500">Actual RR:</span>
                          <span className={`ml-2 ${signal.actualRR >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                            1:{Math.abs(signal.actualRR).toFixed(2)}
                          </span>
                        </div>
                      )}
                    </div>

                    {signal.reasoning && (
                      <div className="mt-2 p-2 bg-gray-800/50 rounded text-xs text-gray-400">
                        <strong>Reasoning:</strong> {signal.reasoning}
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default SignalPerformanceTracker;
