import { useEffect, useState } from 'react';
import { Badge } from '@/components/ui/Badge';
import { TrendingUp, TrendingDown, AlertTriangle, X } from 'lucide-react';
import { getApiUrl } from '@/config/api';

export default function ReversalAlerts() {
  const [reversals, setReversals] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchReversals();
    const interval = setInterval(fetchReversals, 30000); // Check every 30s
    return () => clearInterval(interval);
  }, []);

  const fetchReversals = async () => {
    try {
      const response = await fetch(getApiUrl('/api/reversals/detect'));
      const data = await response.json();
      if (data.success) {
        setReversals(data.reversals || []);
        setError(null);
      } else {
        setError(data.error || 'Failed to fetch reversals');
      }
    } catch (error) {
      console.error('Reversal fetch error:', error);
      setError(error.message);
    }
  };

  const dismissReversal = (index) => {
    setReversals(reversals.filter((_, i) => i !== index));
  };

  if (reversals.length === 0 && !error) return null;

  return (
    <div className="fixed top-20 right-4 z-50 space-y-2 max-w-sm">
      {error && (
        <div className="p-3 bg-red-900/90 border-2 border-red-500 rounded-lg shadow-lg backdrop-blur text-red-100 text-xs">
          Error loading reversals: {error}
        </div>
      )}
      {reversals.map((rev, idx) => (
        <div
          key={`${rev.symbol}-${rev.timestamp}-${idx}`}
          className="p-4 bg-yellow-900/90 border-2 border-yellow-500 rounded-lg shadow-lg backdrop-blur animate-pulse"
        >
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-yellow-400" />
              <span className="font-bold text-yellow-100">FLOW REVERSAL</span>
            </div>
            <button
              onClick={() => dismissReversal(idx)}
              className="text-yellow-300 hover:text-yellow-100 transition-colors"
              title="Dismiss"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
          
          <div className="space-y-2 text-sm text-yellow-50">
            <div className="flex items-center justify-between">
              <span className="font-semibold text-lg font-mono">{rev.symbol}</span>
              <Badge variant={rev.signal === 'REVERSAL_BULLISH' ? 'success' : 'destructive'}>
                {rev.signal === 'REVERSAL_BULLISH' ? 'Now Bullish' : 'Now Bearish'}
              </Badge>
            </div>
            
            <div className="flex items-center gap-2">
              <span className="text-yellow-200">Flow changed:</span>
              <span className="font-mono text-base">{rev.from} → {rev.to}</span>
            </div>
            
            <div className="flex items-center gap-2">
              <span className="text-yellow-200">Premium:</span>
              <span className="font-mono">
                ${(rev.currentPremium / 1000).toFixed(0)}K
              </span>
            </div>
            
            <div className="flex items-center gap-2">
              <span className="text-yellow-200">Price:</span>
              <span className={`font-mono font-semibold ${
                rev.priceChange.startsWith('-') ? 'text-red-300' : 'text-green-300'
              }`}>
                {rev.priceChange}
              </span>
            </div>
            
            <div className="mt-3 pt-3 border-t border-yellow-700 text-xs flex items-start gap-2">
              {rev.signal === 'REVERSAL_BULLISH' ? (
                <>
                  <TrendingUp className="w-4 h-4 mt-0.5 text-green-400 flex-shrink-0" />
                  <span>
                    Institutions flipped <span className="font-bold text-green-400">BULLISH</span>. 
                    Consider longs or exit shorts.
                  </span>
                </>
              ) : (
                <>
                  <TrendingDown className="w-4 h-4 mt-0.5 text-red-400 flex-shrink-0" />
                  <span>
                    Institutions flipped <span className="font-bold text-red-400">BEARISH</span>. 
                    Consider shorts or exit longs.
                  </span>
                </>
              )}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

