import { useState } from 'react';
import { BarChart3, PieChart, Activity } from 'lucide-react';
import PerformanceByTimeframe from './PerformanceByTimeframe';
import EntryTypeAnalysis from './EntryTypeAnalysis';
import SlippageCorrelationAnalysis from './SlippageCorrelationAnalysis';
import type { TimeframeMetrics } from './PerformanceByTimeframe';
import type { EntryTypeMetrics } from './EntryTypeAnalysis';
import type { VolatilityBucket } from './SlippageCorrelationAnalysis';

/**
 * Advanced Metrics Dashboard
 * Unified dashboard showing:
 * - Performance by timeframe
 * - Entry type effectiveness
 * - Slippage correlation analysis
 */

export interface Trade {
  id: string;
  timeframe: string;
  signalType: 'RSI_CROSSOVER' | 'MA_CROSSOVER' | 'BB_BREAKOUT' | 'MACD' | 'SUPPORT_BOUNCE' | 'TREND_CONFIRMATION' | 'NEWS_TRIGGERED';
  entry: number;
  exit: number;
  quantity: number;
  profitable: boolean;
  pnl: number;
  grossPnL?: number;
  slippage: number;
  volatility?: number;
  volume?: number;
  confidence?: number;
  timestamp?: string;
}

export interface AdvancedMetricsDashboardProps {
  trades: Trade[];
  onTimeframeSelect?: (timeframe: string) => void;
  onSignalTypeSelect?: (signalType: string) => void;
  onVolatilityRangeSelect?: (range: VolatilityBucket) => void;
}

type DashboardTab = 'timeframe' | 'entries' | 'slippage';

export default function AdvancedMetricsDashboard({
  trades,
  onTimeframeSelect,
  onSignalTypeSelect,
  onVolatilityRangeSelect,
}: AdvancedMetricsDashboardProps) {
  const [activeTab, setActiveTab] = useState<DashboardTab>('timeframe');
  const [selectedTimeframe, setSelectedTimeframe] = useState<string | null>(null);
  const [selectedSignalType, setSelectedSignalType] = useState<string | null>(null);

  // Filter trades based on selection
  const filteredTrades = trades.filter(trade => {
    if (selectedTimeframe && trade.timeframe !== selectedTimeframe) return false;
    if (selectedSignalType && trade.signalType !== selectedSignalType) return false;
    return true;
  });

  // Overall metrics
  const overallMetrics = {
    totalTrades: trades.length,
    totalProfit: trades.reduce((sum, t) => sum + t.pnl, 0),
    winRate: trades.length > 0 ? (trades.filter(t => t.profitable).length / trades.length) * 100 : 0,
    totalSlippage: trades.reduce((sum, t) => sum + t.slippage, 0),
  };

  const handleTimeframeSelect = (timeframe: string) => {
    setSelectedTimeframe(selectedTimeframe === timeframe ? null : timeframe);
    onTimeframeSelect?.(timeframe);
  };

  const handleSignalTypeSelect = (signalType: string) => {
    setSelectedSignalType(selectedSignalType === signalType ? null : signalType);
    onSignalTypeSelect?.(signalType);
  };

  return (
    <div className="rounded-lg border border-slate-700 bg-slate-900 overflow-hidden">
      {/* Header */}
      <div className="bg-slate-800/50 p-4 border-b border-slate-700">
        <h2 className="text-lg font-bold text-slate-200 mb-3">Advanced Metrics Dashboard</h2>
        
        {/* Overall Stats */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4">
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Total Trades</p>
            <p className="text-lg font-bold text-slate-300">{overallMetrics.totalTrades}</p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Win Rate</p>
            <p className={`text-lg font-bold ${overallMetrics.winRate >= 55 ? 'text-emerald-400' : 'text-amber-400'}`}>
              {overallMetrics.winRate.toFixed(1)}%
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Total P&L</p>
            <p className={`text-lg font-bold ${overallMetrics.totalProfit >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
              ${overallMetrics.totalProfit.toFixed(2)}
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Slippage Cost</p>
            <p className="text-lg font-bold text-red-400">${overallMetrics.totalSlippage.toFixed(2)}</p>
          </div>
        </div>

        {/* Tab Navigation */}
        <div className="flex gap-2">
          <button
            onClick={() => setActiveTab('timeframe')}
            className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-semibold transition-colors ${
              activeTab === 'timeframe'
                ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30'
                : 'bg-slate-700/30 text-slate-400 hover:bg-slate-700/50'
            }`}
          >
            <BarChart3 className="w-4 h-4" />
            Timeframes
          </button>

          <button
            onClick={() => setActiveTab('entries')}
            className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-semibold transition-colors ${
              activeTab === 'entries'
                ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30'
                : 'bg-slate-700/30 text-slate-400 hover:bg-slate-700/50'
            }`}
          >
            <PieChart className="w-4 h-4" />
            Entry Types
          </button>

          <button
            onClick={() => setActiveTab('slippage')}
            className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-semibold transition-colors ${
              activeTab === 'slippage'
                ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30'
                : 'bg-slate-700/30 text-slate-400 hover:bg-slate-700/50'
            }`}
          >
            <Activity className="w-4 h-4" />
            Slippage
          </button>
        </div>

        {/* Active Filters */}
        {(selectedTimeframe || selectedSignalType) && (
          <div className="mt-3 flex flex-wrap gap-2">
            {selectedTimeframe && (
              <button
                onClick={() => setSelectedTimeframe(null)}
                className="inline-flex items-center gap-1 text-xs bg-blue-500/20 text-blue-300 px-2 py-1 rounded border border-blue-500/30 hover:bg-blue-500/30 transition-colors"
              >
                Timeframe: {selectedTimeframe}
                <span className="font-bold">×</span>
              </button>
            )}
            {selectedSignalType && (
              <button
                onClick={() => setSelectedSignalType(null)}
                className="inline-flex items-center gap-1 text-xs bg-purple-500/20 text-purple-300 px-2 py-1 rounded border border-purple-500/30 hover:bg-purple-500/30 transition-colors"
              >
                Signal: {selectedSignalType}
                <span className="font-bold">×</span>
              </button>
            )}
          </div>
        )}
      </div>

      {/* Content */}
      <div className="p-4">
        {activeTab === 'timeframe' && (
          <PerformanceByTimeframe
            trades={filteredTrades.map(t => ({
              id: t.id,
              timeframe: t.timeframe,
              entry: t.entry,
              exit: t.exit,
              quantity: t.quantity,
              profitable: t.profitable,
              pnl: t.pnl,
            }))}
            onTimeframeSelect={handleTimeframeSelect}
          />
        )}

        {activeTab === 'entries' && (
          <EntryTypeAnalysis
            trades={filteredTrades.map(t => ({
              id: t.id,
              signalType: t.signalType,
              entry: t.entry,
              exit: t.exit,
              quantity: t.quantity,
              profitable: t.profitable,
              pnl: t.pnl,
              confidence: t.confidence,
            }))}
            onSignalTypeSelect={handleSignalTypeSelect}
          />
        )}

        {activeTab === 'slippage' && (
          <SlippageCorrelationAnalysis
            trades={filteredTrades.map(t => ({
              id: t.id,
              entry: t.entry,
              exit: t.exit,
              slippage: t.slippage,
              volatility: t.volatility,
              volume: t.volume,
              profitable: t.profitable,
              pnl: t.pnl,
              grossPnL: t.grossPnL || (t.pnl + t.slippage),
              timestamp: t.timestamp,
            }))}
            onVolatilityRangeSelect={onVolatilityRangeSelect}
          />
        )}
      </div>

      {/* Empty State */}
      {trades.length === 0 && (
        <div className="p-8 text-center text-slate-400">
          <BarChart3 className="w-12 h-12 mx-auto mb-3 text-slate-600" />
          <p className="text-lg font-semibold mb-1">No Trading Data</p>
          <p className="text-sm">Start trading to see advanced metrics and analysis</p>
        </div>
      )}
    </div>
  );
}

export type { TimeframeMetrics, EntryTypeMetrics, VolatilityBucket };
