/**
 * ModelAccuracyDashboard Component
 * Individual model accuracy monitoring and comparison
 * OQI-006: Senales ML
 */

import React, { useState, useMemo } from 'react';
import {
  Brain,
  TrendingUp,
  TrendingDown,
  Target,
  BarChart3,
  Activity,
  CheckCircle,
  XCircle,
  Clock,
  RefreshCw,
  ChevronDown,
  ChevronUp,
  Zap,
  Award,
  AlertTriangle,
  Filter,
} from 'lucide-react';

export interface ModelMetrics {
  id: string;
  name: string;
  type: 'classification' | 'regression' | 'ensemble';
  accuracy: number;
  winRate: number;
  totalPredictions: number;
  correctPredictions: number;
  avgConfidence: number;
  sharpeRatio?: number;
  profitFactor?: number;
  mae?: number;
  rmse?: number;
  lastUpdated: string;
  status: 'active' | 'training' | 'inactive';
  performanceBySymbol?: Record<string, { accuracy: number; predictions: number }>;
  performanceByTimeframe?: Record<string, { accuracy: number; predictions: number }>;
  trendData?: { date: string; accuracy: number }[];
}

interface ModelAccuracyDashboardProps {
  models: ModelMetrics[];
  selectedModelId?: string;
  onModelSelect?: (modelId: string) => void;
  onRefresh?: () => void;
  isLoading?: boolean;
  compact?: boolean;
}

const ModelAccuracyDashboard: React.FC<ModelAccuracyDashboardProps> = ({
  models,
  selectedModelId,
  onModelSelect,
  onRefresh,
  isLoading = false,
  compact = false,
}) => {
  const [expandedModelId, setExpandedModelId] = useState<string | null>(selectedModelId || null);
  const [filterType, setFilterType] = useState<'all' | 'classification' | 'regression' | 'ensemble'>('all');
  const [sortBy, setSortBy] = useState<'accuracy' | 'predictions' | 'winRate'>('accuracy');
  const [compareMode, setCompareMode] = useState(false);
  const [compareModels, setCompareModels] = useState<string[]>([]);

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

    if (filterType !== 'all') {
      result = result.filter((m) => m.type === filterType);
    }

    result.sort((a, b) => {
      switch (sortBy) {
        case 'accuracy':
          return b.accuracy - a.accuracy;
        case 'predictions':
          return b.totalPredictions - a.totalPredictions;
        case 'winRate':
          return b.winRate - a.winRate;
        default:
          return 0;
      }
    });

    return result;
  }, [models, filterType, sortBy]);

  // Calculate aggregate stats
  const aggregateStats = useMemo(() => {
    const activeModels = models.filter((m) => m.status === 'active');
    const avgAccuracy = activeModels.reduce((sum, m) => sum + m.accuracy, 0) / (activeModels.length || 1);
    const avgWinRate = activeModels.reduce((sum, m) => sum + m.winRate, 0) / (activeModels.length || 1);
    const totalPredictions = models.reduce((sum, m) => sum + m.totalPredictions, 0);
    const bestModel = models.reduce((best, m) => (m.accuracy > (best?.accuracy || 0) ? m : best), models[0]);

    return { avgAccuracy, avgWinRate, totalPredictions, bestModel, activeModels: activeModels.length };
  }, [models]);

  const getAccuracyColor = (accuracy: number) => {
    if (accuracy >= 70) return 'text-green-400';
    if (accuracy >= 50) return 'text-yellow-400';
    return 'text-red-400';
  };

  const getAccuracyBg = (accuracy: number) => {
    if (accuracy >= 70) return 'bg-green-500';
    if (accuracy >= 50) return 'bg-yellow-500';
    return 'bg-red-500';
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'active':
        return <span className="px-2 py-0.5 bg-green-500/20 text-green-400 rounded text-xs">Active</span>;
      case 'training':
        return <span className="px-2 py-0.5 bg-yellow-500/20 text-yellow-400 rounded text-xs">Training</span>;
      default:
        return <span className="px-2 py-0.5 bg-gray-500/20 text-gray-400 rounded text-xs">Inactive</span>;
    }
  };

  const toggleCompare = (modelId: string) => {
    if (compareModels.includes(modelId)) {
      setCompareModels(compareModels.filter((id) => id !== modelId));
    } else if (compareModels.length < 2) {
      setCompareModels([...compareModels, modelId]);
    }
  };

  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-blue-500/20 rounded-lg">
            <Brain className="w-5 h-5 text-blue-400" />
          </div>
          <div>
            <h3 className="font-semibold text-white">Model Accuracy</h3>
            <p className="text-xs text-gray-500">{aggregateStats.activeModels} active models</p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => setCompareMode(!compareMode)}
            className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${
              compareMode
                ? 'bg-blue-600 text-white'
                : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
            }`}
          >
            Compare
          </button>
          {onRefresh && (
            <button
              onClick={onRefresh}
              disabled={isLoading}
              className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
            </button>
          )}
        </div>
      </div>

      {/* Aggregate Stats */}
      <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 ${getAccuracyColor(aggregateStats.avgAccuracy)}`}>
            {aggregateStats.avgAccuracy.toFixed(1)}%
          </div>
          <div className="text-xs text-gray-500">Avg Accuracy</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="text-lg font-bold text-white">{aggregateStats.avgWinRate.toFixed(1)}%</div>
          <div className="text-xs text-gray-500">Avg Win Rate</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="text-lg font-bold text-white">{aggregateStats.totalPredictions.toLocaleString()}</div>
          <div className="text-xs text-gray-500">Total Predictions</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="text-lg font-bold text-yellow-400 truncate" title={aggregateStats.bestModel?.name}>
            {aggregateStats.bestModel?.name || '-'}
          </div>
          <div className="text-xs text-gray-500">Best Model</div>
        </div>
      </div>

      {/* Filters */}
      {!compact && (
        <div className="flex items-center gap-2 mb-4">
          <Filter className="w-4 h-4 text-gray-500" />
          <select
            value={filterType}
            onChange={(e) => setFilterType(e.target.value as any)}
            className="px-2 py-1 bg-gray-900 border border-gray-700 rounded text-xs text-white"
          >
            <option value="all">All Types</option>
            <option value="classification">Classification</option>
            <option value="regression">Regression</option>
            <option value="ensemble">Ensemble</option>
          </select>
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value as any)}
            className="px-2 py-1 bg-gray-900 border border-gray-700 rounded text-xs text-white"
          >
            <option value="accuracy">Sort by Accuracy</option>
            <option value="predictions">Sort by Predictions</option>
            <option value="winRate">Sort by Win Rate</option>
          </select>
        </div>
      )}

      {/* Compare Section */}
      {compareMode && compareModels.length === 2 && (
        <div className="mb-4 p-4 bg-blue-500/10 border border-blue-500/30 rounded-lg">
          <h4 className="text-sm text-blue-400 font-medium mb-3">Model Comparison</h4>
          <div className="grid grid-cols-2 gap-4">
            {compareModels.map((modelId) => {
              const model = models.find((m) => m.id === modelId);
              if (!model) return null;
              return (
                <div key={model.id} className="p-3 bg-gray-900/50 rounded-lg">
                  <div className="font-medium text-white mb-2">{model.name}</div>
                  <div className="space-y-1 text-xs">
                    <div className="flex justify-between">
                      <span className="text-gray-500">Accuracy</span>
                      <span className={getAccuracyColor(model.accuracy)}>{model.accuracy.toFixed(1)}%</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">Win Rate</span>
                      <span className="text-white">{model.winRate.toFixed(1)}%</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">Predictions</span>
                      <span className="text-white">{model.totalPredictions}</span>
                    </div>
                    {model.profitFactor && (
                      <div className="flex justify-between">
                        <span className="text-gray-500">Profit Factor</span>
                        <span className="text-white">{model.profitFactor.toFixed(2)}</span>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Models List */}
      <div className="space-y-2 max-h-[400px] overflow-y-auto">
        {filteredModels.map((model) => {
          const isExpanded = expandedModelId === model.id;
          const isSelected = compareModels.includes(model.id);

          return (
            <div
              key={model.id}
              className={`p-3 bg-gray-900/50 rounded-lg border transition-all ${
                isExpanded
                  ? 'border-blue-500/50'
                  : isSelected
                  ? 'border-yellow-500/50'
                  : 'border-gray-700/50 hover:border-gray-600'
              }`}
            >
              {/* Header */}
              <div
                onClick={() => {
                  if (compareMode) {
                    toggleCompare(model.id);
                  } else {
                    setExpandedModelId(isExpanded ? null : model.id);
                    onModelSelect?.(model.id);
                  }
                }}
                className="flex items-center justify-between cursor-pointer"
              >
                <div className="flex items-center gap-3">
                  {compareMode && (
                    <div
                      className={`w-5 h-5 rounded border-2 flex items-center justify-center ${
                        isSelected ? 'border-yellow-500 bg-yellow-500/20' : 'border-gray-600'
                      }`}
                    >
                      {isSelected && <CheckCircle className="w-3 h-3 text-yellow-400" />}
                    </div>
                  )}
                  <div className={`p-1.5 rounded ${model.status === 'active' ? 'bg-blue-500/20' : 'bg-gray-500/20'}`}>
                    <Brain className={`w-4 h-4 ${model.status === 'active' ? 'text-blue-400' : 'text-gray-400'}`} />
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-white">{model.name}</span>
                      {getStatusBadge(model.status)}
                    </div>
                    <div className="text-xs text-gray-500">
                      {model.type} • {model.totalPredictions} predictions
                    </div>
                  </div>
                </div>

                <div className="flex items-center gap-4">
                  {/* Accuracy Bar */}
                  <div className="w-24">
                    <div className="flex items-center justify-between text-xs mb-1">
                      <span className="text-gray-500">Accuracy</span>
                      <span className={getAccuracyColor(model.accuracy)}>{model.accuracy.toFixed(1)}%</span>
                    </div>
                    <div className="h-1.5 bg-gray-700 rounded-full overflow-hidden">
                      <div className={`h-full ${getAccuracyBg(model.accuracy)} rounded-full`} style={{ width: `${model.accuracy}%` }} />
                    </div>
                  </div>
                  {!compareMode && (isExpanded ? <ChevronUp className="w-4 h-4 text-gray-500" /> : <ChevronDown className="w-4 h-4 text-gray-500" />)}
                </div>
              </div>

              {/* Expanded Details */}
              {isExpanded && !compareMode && (
                <div className="mt-3 pt-3 border-t border-gray-700/50">
                  {/* Detailed Metrics */}
                  <div className="grid grid-cols-4 gap-3 mb-3">
                    <div className="p-2 bg-gray-800/50 rounded text-center">
                      <div className="text-white font-medium">{model.winRate.toFixed(1)}%</div>
                      <div className="text-xs text-gray-500">Win Rate</div>
                    </div>
                    <div className="p-2 bg-gray-800/50 rounded text-center">
                      <div className="text-white font-medium">{model.avgConfidence.toFixed(1)}%</div>
                      <div className="text-xs text-gray-500">Avg Confidence</div>
                    </div>
                    {model.profitFactor && (
                      <div className="p-2 bg-gray-800/50 rounded text-center">
                        <div className="text-white font-medium">{model.profitFactor.toFixed(2)}</div>
                        <div className="text-xs text-gray-500">Profit Factor</div>
                      </div>
                    )}
                    {model.sharpeRatio && (
                      <div className="p-2 bg-gray-800/50 rounded text-center">
                        <div className="text-white font-medium">{model.sharpeRatio.toFixed(2)}</div>
                        <div className="text-xs text-gray-500">Sharpe Ratio</div>
                      </div>
                    )}
                  </div>

                  {/* Performance by Symbol */}
                  {model.performanceBySymbol && Object.keys(model.performanceBySymbol).length > 0 && (
                    <div className="mb-3">
                      <div className="text-xs text-gray-400 mb-2">Performance by Symbol</div>
                      <div className="flex flex-wrap gap-2">
                        {Object.entries(model.performanceBySymbol).slice(0, 5).map(([symbol, data]) => (
                          <div key={symbol} className="px-2 py-1 bg-gray-800/50 rounded text-xs">
                            <span className="text-gray-400">{symbol}:</span>
                            <span className={`ml-1 ${getAccuracyColor(data.accuracy)}`}>{data.accuracy.toFixed(0)}%</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Performance by Timeframe */}
                  {model.performanceByTimeframe && Object.keys(model.performanceByTimeframe).length > 0 && (
                    <div className="mb-3">
                      <div className="text-xs text-gray-400 mb-2">Performance by Timeframe</div>
                      <div className="flex flex-wrap gap-2">
                        {Object.entries(model.performanceByTimeframe).map(([tf, data]) => (
                          <div key={tf} className="px-2 py-1 bg-gray-800/50 rounded text-xs">
                            <span className="text-gray-400">{tf}:</span>
                            <span className={`ml-1 ${getAccuracyColor(data.accuracy)}`}>{data.accuracy.toFixed(0)}%</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Last Updated */}
                  <div className="flex items-center gap-2 text-xs text-gray-500">
                    <Clock className="w-3 h-3" />
                    Last updated: {formatDate(model.lastUpdated)}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default ModelAccuracyDashboard;
