import { useState } from 'react';
import { Badge } from '../ui/Badge';

export function ScoreBreakdownTooltip({ row, children }) {
  const [isHovered, setIsHovered] = useState(false);
  
  const score = row.rocketScore || row.rocket_score || 0;
  const premium = row.premium_num || 0;
  const bullTotal = row.bull_total || 0;
  const bearTotal = row.bear_total || 0;
  const totalPrem = bullTotal + bearTotal;
  const netPrem = bullTotal - bearTotal;
  const vol = row.vol_num || 0;
  const oi = row.oi_num || 0;
  const session = row.session_bucket || 'RTH';
  const hasCatalyst = row.near_alert_type || false;
  const isOTM = (row.cp_norm === 'CALL' && row.strike_num > row.spot_num) ||
                (row.cp_norm === 'PUT' && row.strike_num < row.spot_num);
  const tapeAligned = row.tapeAligned || row.tape_alignment === 1;
  
  // Calculate score breakdown (matching backend logic)
  let breakdown = [];
  let total = 0;
  
  // Premium tier (0-3 points)
  let premiumPts = 0;
  if (premium >= 2000000) premiumPts = 3.0;
  else if (premium >= 800000) premiumPts = 2.0;
  else if (premium >= 200000) premiumPts = 1.0;
  breakdown.push({ label: 'Premium Tier', points: premiumPts, max: 3.0, value: `$${(premium / 1000000).toFixed(2)}M` });
  total += premiumPts;
  
  // Net premium imbalance (-1.5 to +1.5 points)
  let netPremPts = 0;
  if (totalPrem > 0) {
    netPremPts = 1.5 * (netPrem / totalPrem);
  }
  breakdown.push({ label: 'Net Imbalance', points: netPremPts, max: 1.5, value: netPrem > 0 ? 'Bullish' : 'Bearish' });
  total += netPremPts;
  
  // Vol > OI (1.2 points)
  let volOIPts = 0;
  if (vol > oi) volOIPts = 1.2;
  breakdown.push({ label: 'Vol > OI', points: volOIPts, max: 1.2, value: vol > oi ? 'New Positions' : 'Existing' });
  total += volOIPts;
  
  // Session weight (0-1 point)
  const sessionWeights = { RTH: 1.0, POST: 0.5, PRE: 0.3, OFF: 0 };
  const sessionPts = sessionWeights[session] || 0;
  breakdown.push({ label: 'Session', points: sessionPts, max: 1.0, value: session });
  total += sessionPts;
  
  // Catalyst flag (1 point)
  const catalystPts = hasCatalyst ? 1.0 : 0;
  breakdown.push({ label: 'Catalyst', points: catalystPts, max: 1.0, value: hasCatalyst ? 'Yes' : 'No' });
  total += catalystPts;
  
  // OTM bias (0.8 points)
  const otmPts = isOTM ? 0.8 : 0;
  breakdown.push({ label: 'OTM Bias', points: otmPts, max: 0.8, value: isOTM ? 'OTM' : 'ITM' });
  total += otmPts;
  
  // Tape alignment (0.5 points)
  const tapePts = tapeAligned ? 0.5 : 0;
  breakdown.push({ label: 'Tape Align', points: tapePts, max: 0.5, value: tapeAligned ? 'Aligned' : 'Not Aligned' });
  total += tapePts;
  
  const conviction = score >= 5 ? 'HIGH CONVICTION' : score >= 3.5 ? 'MEDIUM CONVICTION' : 'LOW CONVICTION';
  const convictionColor = score >= 5 ? 'text-green-400' : score >= 3.5 ? 'text-yellow-400' : 'text-slate-400';
  
  return (
    <div 
      className="relative inline-block"
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {children}
      
      {isHovered && (
        <div className="absolute left-0 top-full mt-2 z-50 w-80 bg-slate-900 border border-slate-700 rounded-lg shadow-2xl p-4 text-sm">
          <div className="space-y-3">
            {/* Header */}
            <div className="border-b border-slate-700 pb-2">
              <div className="font-bold text-base text-slate-100">
                SCORE BREAKDOWN: {score.toFixed(1)} / 10
              </div>
              <div className={`text-xs mt-1 ${convictionColor} font-semibold`}>
                → {conviction} SIGNAL
              </div>
            </div>
            
            {/* Breakdown Items */}
            <div className="space-y-2">
              {breakdown.map((item, idx) => (
                <div key={idx} className="flex items-start justify-between text-xs">
                  <div className="flex-1">
                    <div className="text-slate-400">{item.label}:</div>
                    <div className="text-slate-300 text-xs mt-0.5">{item.value}</div>
                  </div>
                  <div className="text-right ml-4">
                    <div className={item.points > 0 ? 'text-green-400' : 'text-slate-500'}>
                      {item.points > 0 ? '✅' : '❌'} {item.points.toFixed(1)} pts
                    </div>
                    <div className="text-slate-500 text-xs">(max {item.max})</div>
                  </div>
                </div>
              ))}
            </div>
            
            {/* Total */}
            <div className="border-t border-slate-700 pt-2 mt-2">
              <div className="flex justify-between items-center">
                <span className="text-slate-300 font-semibold">Total:</span>
                <span className="text-slate-100 font-bold text-base">{total.toFixed(1)} pts</span>
              </div>
              <div className="text-xs text-slate-400 mt-1">
                {score >= 5 ? '→ Trade this signal' : score >= 3.5 ? '→ Monitor for confirmation' : '→ Wait for stronger signal'}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

