import { useEffect, useState } from 'react';
import { Badge } from '@/components/ui/Badge';
import { Zap, TrendingUp, X } from 'lucide-react';
import { getApiUrl } from '@/config/api';
import { playAlertSound } from '@/utils/audio';

export default function ConvergenceAlerts() {
  const [convergences, setConvergences] = useState([]);
  const [dismissed, setDismissed] = useState(new Set());
  const [previousCount, setPreviousCount] = useState(0);

  useEffect(() => {
    fetchConvergences();
    const interval = setInterval(fetchConvergences, 20000); // Check every 20s
    return () => clearInterval(interval);
  }, []);

  const fetchConvergences = async () => {
    try {
      const response = await fetch(getApiUrl('/api/convergence/detect?lookback=10'));
      const data = await response.json();
      
      if (data.success && data.convergences && data.convergences.length > 0) {
        // Filter out dismissed convergences
        const activeConvergences = data.convergences.filter(c => 
          !dismissed.has(c.symbol)
        );
        
        // Check for new convergences (more than before)
        if (activeConvergences.length > previousCount && previousCount > 0) {
          // New convergence detected - play sound
          playAlertSound();
        }
        
        setConvergences(activeConvergences);
        setPreviousCount(activeConvergences.length);
      } else {
        setConvergences([]);
        setPreviousCount(0);
      }
    } catch (error) {
      console.error('Convergence fetch error:', error);
    }
  };

  const handleDismiss = (symbol) => {
    setDismissed(new Set([...dismissed, symbol]));
    setConvergences(convergences.filter(c => c.symbol !== symbol));
  };

  if (convergences.length === 0) return null;

  return (
    <div className="fixed top-4 left-1/2 -translate-x-1/2 z-50 space-y-3 max-w-2xl w-full px-4">
      {convergences.map((conv) => (
        <div
          key={conv.symbol}
          className="p-4 bg-gradient-to-r from-purple-900/95 to-pink-900/95 border-2 border-purple-400 rounded-lg shadow-2xl backdrop-blur animate-pulse-slow"
        >
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-3">
              <Zap className="w-6 h-6 text-yellow-400 animate-pulse" />
              <span className="font-bold text-xl text-white">
                🔥 CONVERGENCE EVENT
              </span>
            </div>
            <button
              onClick={() => handleDismiss(conv.symbol)}
              className="text-purple-200 hover:text-white text-xl transition-colors"
              title="Dismiss"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
          
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <span className="font-bold text-2xl text-white font-mono">{conv.symbol}</span>
              <Badge variant="destructive" className="text-sm animate-pulse">
                {conv.signalCount} SIGNALS
              </Badge>
            </div>
            
            <div className="text-sm text-purple-100">
              <div className="font-semibold mb-1">Institutional Footprints:</div>
              <div className="pl-2">{conv.reasoning || 'Multiple signals detected'}</div>
            </div>
            
            <div className="grid grid-cols-3 gap-2 text-xs text-purple-200">
              <div>
                <div className="font-semibold">Time Window</div>
                <div className="text-white font-mono">{conv.timeWindow} min</div>
              </div>
              <div>
                <div className="font-semibold">Notional</div>
                <div className="text-white font-mono">
                  ${(conv.totalNotional / 1e6).toFixed(1)}M
                </div>
              </div>
              <div>
                <div className="font-semibold">Rocket Score</div>
                <div className="text-white font-mono">{conv.rocketScore.toFixed(1)}/10</div>
              </div>
            </div>
            
            {conv.currentPrice > 0 && (
              <div className="text-xs text-purple-200">
                <span className="font-semibold">Current Price: </span>
                <span className="text-white font-mono">${conv.currentPrice.toFixed(2)}</span>
              </div>
            )}
            
            <div className="pt-3 border-t border-purple-700 text-sm text-purple-100 flex items-center gap-2">
              <TrendingUp className="w-4 h-4 flex-shrink-0" />
              <span className="font-semibold">
                Multiple institutional signals firing together = HIGH CONVICTION SETUP
              </span>
            </div>
            
            <div className="flex gap-2 mt-3">
              <button
                onClick={() => {
                  // Navigate to trade plan or symbol detail
                  window.location.href = `#${conv.symbol}`;
                  // Scroll to symbol in table if available
                  const symbolElement = document.querySelector(`[data-symbol="${conv.symbol}"]`);
                  if (symbolElement) {
                    symbolElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                  }
                }}
                className="flex-1 px-4 py-2 bg-purple-600 hover:bg-purple-500 text-white rounded font-semibold transition-colors"
              >
                View Trade Plan
              </button>
              <button
                onClick={() => handleDismiss(conv.symbol)}
                className="px-4 py-2 bg-purple-800 hover:bg-purple-700 text-purple-200 rounded transition-colors"
              >
                Dismiss
              </button>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

