import { useState, useEffect } from 'react';
import { Badge } from '@/components/ui/Badge';
import { TrendingUp, TrendingDown, RefreshCw, Calendar, Search, BarChart3 } from 'lucide-react';
import { getApiUrl } from '@/config/api';

export default function BacktestPanel() {
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
  const [minPremium, setMinPremium] = useState(80000);
  const [symbols, setSymbols] = useState([]);
  const [selectedSymbol, setSelectedSymbol] = useState(null);
  const [performance, setPerformance] = useState(null);
  const [loading, setLoading] = useState(false);
  const [loadingPerformance, setLoadingPerformance] = useState(false);

  // Fetch symbols for selected date
  const fetchSymbolsForDate = async (date, premium = minPremium) => {
    setLoading(true);
    try {
      const response = await fetch(
        getApiUrl(`/api/backtest/date-analysis?date=${date}&minRocketScore=2&maxRocketScore=3&minPremium=${premium}`)
      );
      const data = await response.json();
      if (data.success) {
        // Filter symbols that appeared more than 3 times (using total_trades or signal_periods)
        const frequentSymbols = data.symbols.filter(s => (s.total_trades || s.signal_count || 0) > 3);
        setSymbols(frequentSymbols);
      }
    } catch (error) {
      console.error('Error fetching symbols:', error);
    } finally {
      setLoading(false);
    }
  };

  // Fetch performance for selected symbol
  const fetchSymbolPerformance = async (symbol, date) => {
    setLoadingPerformance(true);
    setSelectedSymbol(symbol);
    try {
      const response = await fetch(
        getApiUrl(`/api/backtest/symbol-performance?symbol=${symbol}&entryDate=${date}&daysForward=7`)
      );
      const data = await response.json();
      if (data.success) {
        setPerformance(data);
      }
    } catch (error) {
      console.error('Error fetching performance:', error);
    } finally {
      setLoadingPerformance(false);
    }
  };

  useEffect(() => {
    if (selectedDate) {
      fetchSymbolsForDate(selectedDate, minPremium);
    }
  }, [selectedDate, minPremium]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold">Historical Signal Backtest</h2>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <Calendar className="w-4 h-4 text-slate-400" />
            <input
              type="date"
              value={selectedDate}
              onChange={(e) => setSelectedDate(e.target.value)}
              className="px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-slate-200"
              max={new Date().toISOString().split('T')[0]}
            />
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm text-slate-400 whitespace-nowrap">Min Premium:</span>
            <div className="relative">
              <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 text-sm">$</span>
              <input
                type="number"
                value={minPremium}
                onChange={(e) => {
                  const value = parseInt(e.target.value) || 0;
                  setMinPremium(value);
                }}
                className="pl-7 pr-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 w-32"
                placeholder="80000"
                min="0"
                step="1000"
              />
            </div>
          </div>
          <button
            onClick={() => fetchSymbolsForDate(selectedDate, minPremium)}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-lg transition-colors flex items-center gap-2"
            disabled={loading}
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </button>
        </div>
      </div>

      {/* Date Selection Info */}
      <div className="p-4 bg-slate-900 border border-slate-800 rounded-lg">
        <p className="text-sm text-slate-400">
          📅 Analyzing signals from <span className="font-semibold text-slate-200">{selectedDate}</span>
        </p>
        <p className="text-xs text-slate-500 mt-1">
          Showing symbols with 2-3 rocket scores that had more than 3 option trades with premium &gt; ${(minPremium / 1000).toFixed(0)}K
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Left: Symbols List */}
        <div className="space-y-4">
          <h3 className="text-lg font-semibold flex items-center gap-2">
            <Search className="w-5 h-5" />
            Symbols with High Signal Activity
          </h3>

          {loading ? (
            <div className="text-center py-12">
              <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
              <div className="mt-4 text-slate-400">Loading symbols...</div>
            </div>
          ) : symbols.length === 0 ? (
            <div className="text-center py-12 text-slate-400">
              No symbols found for this date. Try a different date.
            </div>
          ) : (
            <div className="space-y-2 max-h-[600px] overflow-y-auto">
              {symbols.map((symbol) => (
                <div
                  key={symbol.symbol_norm}
                  onClick={() => fetchSymbolPerformance(symbol.symbol_norm, selectedDate)}
                  className={`p-4 bg-slate-900 border rounded-lg cursor-pointer transition-all ${
                    selectedSymbol === symbol.symbol_norm
                      ? 'border-blue-500 bg-slate-800'
                      : 'border-slate-800 hover:border-slate-700'
                  }`}
                >
                  <div className="flex items-center justify-between mb-2">
                    <h4 className="text-lg font-bold text-slate-200">{symbol.symbol_norm}</h4>
                    <Badge
                      variant={(symbol.total_trades || symbol.signal_count || 0) > 10 ? 'success' : 'warning'}
                      className="text-xs"
                    >
                      {symbol.total_trades || symbol.signal_count || 0} trades
                      {symbol.signal_periods ? ` (${symbol.signal_periods} periods)` : ''}
                    </Badge>
                  </div>
                  
                  <div className="grid grid-cols-2 gap-2 text-xs mb-3">
                    <div>
                      <span className="text-slate-500">Total Premium:</span>
                      <span className="ml-2 text-slate-200 font-semibold">
                        ${((Number(symbol.total_premium) || 0) / 1000000).toFixed(2)}M
                      </span>
                    </div>
                    <div>
                      <span className="text-slate-500">Avg Rocket:</span>
                      <span className="ml-2 text-slate-200 font-semibold">
                        {symbol.avg_rocket_score != null ? Number(symbol.avg_rocket_score).toFixed(1) : 'N/A'}
                      </span>
                    </div>
                    <div>
                      <span className="text-slate-500">Entry Price:</span>
                      <span className="ml-2 text-slate-200 font-semibold">
                        {symbol.entry_price != null ? `$${Number(symbol.entry_price).toFixed(2)}` : 'N/A'}
                      </span>
                    </div>
                    <div>
                      <span className="text-slate-500">Direction:</span>
                      <span className="ml-2 text-slate-200 font-semibold">
                        {symbol.directions || 'Mixed'}
                      </span>
                    </div>
                  </div>
                  
                  {/* BULL/BEAR Breakdown */}
                  {(symbol.bull_count > 0 || symbol.bear_count > 0) && (
                    <div className="pt-3 border-t border-slate-700 space-y-2">
                      {symbol.bull_count > 0 && (
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <span className="text-green-400 font-semibold">🟢 BULL:</span>
                            <span className="text-slate-300">{symbol.bull_count} signals</span>
                          </div>
                          <div className="text-right">
                            <div className="text-slate-200 font-semibold">
                              ${((Number(symbol.bull_premium) || 0) / 1000000).toFixed(2)}M
                            </div>
                            <div className="text-slate-400 text-xs">
                              ${((Number(symbol.bull_min_premium) || 0) / 1000).toFixed(0)}K - ${((Number(symbol.bull_max_premium) || 0) / 1000).toFixed(0)}K
                            </div>
                          </div>
                        </div>
                      )}
                      {symbol.bear_count > 0 && (
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <span className="text-red-400 font-semibold">🔴 BEAR:</span>
                            <span className="text-slate-300">{symbol.bear_count} signals</span>
                          </div>
                          <div className="text-right">
                            <div className="text-slate-200 font-semibold">
                              ${((Number(symbol.bear_premium) || 0) / 1000000).toFixed(2)}M
                            </div>
                            <div className="text-slate-400 text-xs">
                              ${((Number(symbol.bear_min_premium) || 0) / 1000).toFixed(0)}K - ${((Number(symbol.bear_max_premium) || 0) / 1000).toFixed(0)}K
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                  
                  {/* Predictive Factors */}
                  <div className="pt-3 border-t border-slate-700 space-y-2">
                    <h6 className="text-xs font-semibold text-slate-400 mb-2">📊 Predictive Factors:</h6>
                    
                    {/* Moneyness */}
                    {(symbol.itm_count > 0 || symbol.otm_count > 0) && (
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-slate-500">Moneyness:</span>
                        <div className="text-right">
                          <span className="text-green-400">{symbol.itm_count || 0} ITM</span>
                          <span className="text-slate-500 mx-1">/</span>
                          <span className="text-yellow-400">{symbol.otm_count || 0} OTM</span>
                        </div>
                      </div>
                    )}
                    
                    {/* DTE */}
                    {symbol.avg_dte != null && (
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-slate-500">Avg DTE:</span>
                        <span className="text-slate-200 font-semibold">
                          {Number(symbol.avg_dte).toFixed(0)} days
                          {symbol.most_common_dte_bucket && (
                            <span className="text-slate-400 ml-1">({symbol.most_common_dte_bucket})</span>
                          )}
                        </span>
                      </div>
                    )}
                    
                    {/* Session Distribution */}
                    {(symbol.rth_count > 0 || symbol.pre_count > 0 || symbol.post_count > 0) && (
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-slate-500">Session:</span>
                        <div className="text-right">
                          <span className="text-blue-400">{symbol.rth_count || 0} RTH</span>
                          {symbol.pre_count > 0 && (
                            <>
                              <span className="text-slate-500 mx-1">/</span>
                              <span className="text-purple-400">{symbol.pre_count} PRE</span>
                            </>
                          )}
                          {symbol.post_count > 0 && (
                            <>
                              <span className="text-slate-500 mx-1">/</span>
                              <span className="text-orange-400">{symbol.post_count} POST</span>
                            </>
                          )}
                        </div>
                      </div>
                    )}
                    
                    {/* Catalyst */}
                    {symbol.catalyst_count > 0 && (
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-slate-500">⚡ Catalyst:</span>
                        <span className="text-yellow-400 font-semibold">
                          {symbol.catalyst_count} signals ({Number(symbol.pct_with_catalyst || 0).toFixed(0)}%)
                        </span>
                      </div>
                    )}
                    
                    {/* Volume/OI Ratio */}
                    {symbol.avg_vol_oi_ratio != null && (
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-slate-500">Vol/OI Ratio:</span>
                        <span className={`font-semibold ${
                          Number(symbol.avg_vol_oi_ratio) > 1 ? 'text-green-400' : 'text-slate-400'
                        }`}>
                          {Number(symbol.avg_vol_oi_ratio).toFixed(2)}x
                          {symbol.vol_exceeds_oi_count > 0 && (
                            <span className="text-slate-400 ml-1">
                              ({symbol.vol_exceeds_oi_count} trades)
                            </span>
                          )}
                        </span>
                      </div>
                    )}
                    
                    {/* Strike Clustering */}
                    {symbol.unique_strikes > 0 && (
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-slate-500">Strike Clustering:</span>
                        <span className="text-slate-200 font-semibold">
                          {symbol.unique_strikes} unique strikes
                          {symbol.avg_trades_per_strike > 0 && (
                            <span className="text-slate-400 ml-1">
                              ({Number(symbol.avg_trades_per_strike).toFixed(1)} avg/strike)
                            </span>
                          )}
                          {symbol.max_trades_at_single_strike > 1 && (
                            <span className="text-blue-400 ml-1">
                              (max: {symbol.max_trades_at_single_strike})
                            </span>
                          )}
                        </span>
                      </div>
                    )}
                    
                    {/* IV */}
                    {symbol.avg_iv != null && (
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-slate-500">Avg IV:</span>
                        <span className="text-slate-200 font-semibold">
                          {Number(symbol.avg_iv).toFixed(1)}%
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Right: Performance Analysis */}
        <div className="space-y-4">
          <h3 className="text-lg font-semibold flex items-center gap-2">
            <BarChart3 className="w-5 h-5" />
            Performance Analysis
          </h3>

          {loadingPerformance ? (
            <div className="text-center py-12">
              <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
              <div className="mt-4 text-slate-400">Analyzing performance...</div>
            </div>
          ) : !performance ? (
            <div className="text-center py-12 text-slate-400">
              Select a symbol to view performance analysis
            </div>
          ) : (
            <div className="space-y-4">
              {/* Summary Card */}
              <div className={`p-6 rounded-lg border-2 ${
                performance.performance.wouldBeProfitable
                  ? 'bg-green-900/20 border-green-600/50'
                  : 'bg-red-900/20 border-red-600/50'
              }`}>
                <div className="flex items-center justify-between mb-4">
                  <h4 className="text-xl font-bold">{performance.symbol}</h4>
                  {performance.performance.wouldBeProfitable ? (
                    <TrendingUp className="w-8 h-8 text-green-400" />
                  ) : (
                    <TrendingDown className="w-8 h-8 text-red-400" />
                  )}
                </div>
                
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-slate-400">Entry Price:</span>
                    <span className="font-semibold">${Number(performance.entryPrice || 0).toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">Final Change:</span>
                    <span className={`font-semibold ${
                      Number(performance.performance?.finalGain || 0) >= 0 ? 'text-green-400' : 'text-red-400'
                    }`}>
                      {Number(performance.performance?.finalGain || 0) >= 0 ? '+' : ''}
                      {Number(performance.performance?.finalGain || 0).toFixed(2)}%
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">Max Gain:</span>
                    <span className="font-semibold text-green-400">
                      +{Number(performance.performance?.maxGain || 0).toFixed(2)}%
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">Max Loss:</span>
                    <span className="font-semibold text-red-400">
                      {Number(performance.performance?.maxLoss || 0).toFixed(2)}%
                    </span>
                  </div>
                </div>

                <div className="mt-4 p-3 bg-slate-800/50 rounded">
                  <p className="text-sm text-slate-300">
                    {performance.performance.profitReason}
                  </p>
                  
                  {/* Detailed Analysis for Mixed Signals */}
                  {performance.performance.detailedAnalysis && (
                    <div className="mt-4 pt-4 border-t border-slate-700">
                      <h6 className="text-xs font-semibold text-slate-400 mb-3">Mixed Signals Breakdown:</h6>
                      <div className="space-y-2">
                        <div className="flex items-start gap-2">
                          <span className="text-xs text-slate-500 w-16">BULL:</span>
                          <div className="flex-1">
                            <span className={`text-xs font-semibold ${
                              performance.performance.detailedAnalysis.bullSignals.profitable 
                                ? 'text-green-400' 
                                : 'text-red-400'
                            }`}>
                              {performance.performance.detailedAnalysis.bullSignals.result}
                            </span>
                            <p className="text-xs text-slate-400 mt-1">
                              {performance.performance.detailedAnalysis.bullSignals.explanation}
                            </p>
                          </div>
                        </div>
                        <div className="flex items-start gap-2">
                          <span className="text-xs text-slate-500 w-16">BEAR:</span>
                          <div className="flex-1">
                            <span className={`text-xs font-semibold ${
                              performance.performance.detailedAnalysis.bearSignals.profitable 
                                ? 'text-green-400' 
                                : 'text-red-400'
                            }`}>
                              {performance.performance.detailedAnalysis.bearSignals.result}
                            </span>
                            <p className="text-xs text-slate-400 mt-1">
                              {performance.performance.detailedAnalysis.bearSignals.explanation}
                            </p>
                          </div>
                        </div>
                        <div className="mt-3 pt-2 border-t border-slate-700">
                          <p className="text-xs font-semibold text-blue-400">
                            💡 {performance.performance.detailedAnalysis.recommendation}
                          </p>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* Price Chart */}
              {performance.priceHistory && performance.priceHistory.length > 0 && (
                <div className="p-4 bg-slate-900 border border-slate-800 rounded-lg">
                  <h5 className="text-sm font-semibold mb-3 text-slate-300">Price Movement (7 Days)</h5>
                  <div className="space-y-2">
                    {performance.priceHistory.map((day) => (
                      <div key={day.date} className="flex items-center gap-2">
                        <div className="w-20 text-xs text-slate-400">
                          {new Date(day.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                        </div>
                        <div className="flex-1 bg-slate-800 rounded h-6 relative">
                          <div
                            className={`h-full rounded ${
                              Number(day.changePct || 0) >= 0 ? 'bg-green-500/50' : 'bg-red-500/50'
                            }`}
                            style={{
                              width: `${Math.min(Math.abs(Number(day.changePct || 0)) * 10, 100)}%`,
                              marginLeft: Number(day.changePct || 0) < 0 ? 'auto' : '0',
                              marginRight: Number(day.changePct || 0) < 0 ? '0' : 'auto'
                            }}
                          />
                        </div>
                        <div className={`w-16 text-xs text-right font-semibold ${
                          Number(day.changePct || 0) >= 0 ? 'text-green-400' : 'text-red-400'
                        }`}>
                          {Number(day.changePct || 0) >= 0 ? '+' : ''}{Number(day.changePct || 0).toFixed(2)}%
                        </div>
                        <div className="w-20 text-xs text-slate-300 text-right">
                          ${Number(day.close || 0).toFixed(2)}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Signal Details */}
              {performance.signals && (
                <div className="p-4 bg-slate-900 border border-slate-800 rounded-lg">
                  <h5 className="text-sm font-semibold mb-3 text-slate-300">Signal Details</h5>
                  <div className="grid grid-cols-2 gap-2 text-xs mb-3">
                    <div>
                      <span className="text-slate-500">Signal Count:</span>
                      <span className="ml-2 text-slate-200 font-semibold">
                        {performance.signals.signal_count || 0}
                      </span>
                    </div>
                    <div>
                      <span className="text-slate-500">Total Premium:</span>
                      <span className="ml-2 text-slate-200 font-semibold">
                        ${((Number(performance.signals.total_premium) || 0) / 1000000).toFixed(2)}M
                      </span>
                    </div>
                    <div>
                      <span className="text-slate-500">Max Rocket:</span>
                      <span className="ml-2 text-slate-200 font-semibold">
                        {performance.signals.max_rocket_score != null ? Number(performance.signals.max_rocket_score).toFixed(1) : 'N/A'}
                      </span>
                    </div>
                    <div>
                      <span className="text-slate-500">Direction:</span>
                      <span className="ml-2 text-slate-200 font-semibold">
                        {performance.signals.directions || 'Mixed'}
                      </span>
                    </div>
                  </div>
                  
                  {/* Predictive Factors in Signal Details */}
                  {(performance.signals.itm_count > 0 || performance.signals.otm_count > 0 || 
                    performance.signals.avg_dte != null || performance.signals.catalyst_count > 0) && (
                    <div className="pt-3 border-t border-slate-700 space-y-2">
                      <h6 className="text-xs font-semibold text-slate-400 mb-2">📊 Signal Quality Factors:</h6>
                      
                      {/* Moneyness */}
                      {(performance.signals.itm_count > 0 || performance.signals.otm_count > 0) && (
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-slate-500">Moneyness:</span>
                          <div className="text-right">
                            <span className="text-green-400">{performance.signals.itm_count || 0} ITM</span>
                            <span className="text-slate-500 mx-1">/</span>
                            <span className="text-yellow-400">{performance.signals.otm_count || 0} OTM</span>
                          </div>
                        </div>
                      )}
                      
                      {/* DTE */}
                      {performance.signals.avg_dte != null && (
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-slate-500">Avg DTE:</span>
                          <span className="text-slate-200 font-semibold">
                            {Number(performance.signals.avg_dte).toFixed(0)} days
                            {performance.signals.most_common_dte_bucket && (
                              <span className="text-slate-400 ml-1">({performance.signals.most_common_dte_bucket})</span>
                            )}
                          </span>
                        </div>
                      )}
                      
                      {/* Session Distribution */}
                      {(performance.signals.rth_count > 0 || performance.signals.pre_count > 0 || performance.signals.post_count > 0) && (
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-slate-500">Session:</span>
                          <div className="text-right">
                            <span className="text-blue-400">{performance.signals.rth_count || 0} RTH</span>
                            {performance.signals.pre_count > 0 && (
                              <>
                                <span className="text-slate-500 mx-1">/</span>
                                <span className="text-purple-400">{performance.signals.pre_count} PRE</span>
                              </>
                            )}
                            {performance.signals.post_count > 0 && (
                              <>
                                <span className="text-slate-500 mx-1">/</span>
                                <span className="text-orange-400">{performance.signals.post_count} POST</span>
                              </>
                            )}
                          </div>
                        </div>
                      )}
                      
                      {/* Catalyst */}
                      {performance.signals.catalyst_count > 0 && (
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-slate-500">⚡ Catalyst:</span>
                          <span className="text-yellow-400 font-semibold">
                            {performance.signals.catalyst_count} signals ({Number(performance.signals.pct_with_catalyst || 0).toFixed(0)}%)
                          </span>
                        </div>
                      )}
                      
                      {/* Volume/OI Ratio */}
                      {performance.signals.avg_vol_oi_ratio != null && (
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-slate-500">Vol/OI Ratio:</span>
                          <span className={`font-semibold ${
                            Number(performance.signals.avg_vol_oi_ratio) > 1 ? 'text-green-400' : 'text-slate-400'
                          }`}>
                            {Number(performance.signals.avg_vol_oi_ratio).toFixed(2)}x
                            {performance.signals.vol_exceeds_oi_count > 0 && (
                              <span className="text-slate-400 ml-1">
                                ({performance.signals.vol_exceeds_oi_count} trades)
                              </span>
                            )}
                          </span>
                        </div>
                      )}
                      
                      {/* Strike Clustering */}
                      {performance.signals.unique_strikes > 0 && (
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-slate-500">Strike Clustering:</span>
                          <span className="text-slate-200 font-semibold">
                            {performance.signals.unique_strikes} unique strikes
                          </span>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

