import { useState, useEffect } from 'react';
import { Badge } from '@/components/ui/Badge';
import { Input } from '@/components/ui/input';
import { Bell, TrendingUp, TrendingDown, AlertTriangle, Calendar, Clock } from 'lucide-react';
import { requestNotificationPermission, sendNotification } from '@/utils/notifications';

export default function AlertsFeed() {
  const [alerts, setAlerts] = useState([]);
  const [filter, setFilter] = useState('ALL');
  const [wsConnected, setWsConnected] = useState(false);
  const [useHistorical, setUseHistorical] = useState(false);
  const [historicalDate, setHistoricalDate] = useState(new Date().toISOString().split('T')[0]);
  const [historicalTime, setHistoricalTime] = useState('16:00:00');
  const [hoursBack, setHoursBack] = useState(4);

  useEffect(() => {
    // Request notification permission on mount
    requestNotificationPermission();

    // Fetch initial alerts
    fetchAlerts();

    // Only connect WebSocket if not using historical data
    if (useHistorical) {
      return;
    }

    // WebSocket connection for real-time alerts
    // Uses relative URL which will be proxied by nginx or use configured WS URL
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${wsProtocol}//${window.location.host}/ws/alerts`;
    
    const ws = new WebSocket(wsUrl);

    ws.onopen = () => {
      console.log('Connected to alerts WebSocket');
      setWsConnected(true);
    };

    ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        if (message.type === 'NEW_ALERT' && message.data) {
          const newAlert = message.data;
          setAlerts(prev => [newAlert, ...prev].slice(0, 50)); // Keep last 50

          // Desktop notification for critical alerts
          if (newAlert.priority === 'HIGH') {
            sendNotification('⚠️ Critical Alert', {
              body: `${newAlert.symbol}: ${newAlert.type}\n${newAlert.message}`,
              tag: `alert-${newAlert.symbol}-${Date.now()}`,
              requireInteraction: false,
            });
          }
        }
      } catch (error) {
        console.error('Failed to parse WebSocket message:', error);
      }
    };

    ws.onerror = (error) => {
      console.error('WebSocket error:', error);
      setWsConnected(false);
    };

    ws.onclose = () => {
      console.log('Disconnected from alerts WebSocket');
      setWsConnected(false);
    };

    return () => {
      ws.close();
    };
  }, [useHistorical]);

  const fetchAlerts = async () => {
    try {
      let url = getApiUrl('/api/alerts/recent');
      if (useHistorical && historicalDate) {
        const params = new URLSearchParams({ 
          date: historicalDate,
          hours: hoursBack.toString()
        });
        if (historicalTime) {
          params.append('time', historicalTime);
        }
        url += `?${params.toString()}`;
      }
      
      const response = await fetch(url);
      const data = await response.json();
      if (data.success) {
        setAlerts(data.data || []);
      }
    } catch (error) {
      console.error('Failed to fetch alerts:', error);
    }
  };
  
  useEffect(() => {
    if (useHistorical) {
      fetchAlerts();
    }
  }, [useHistorical, historicalDate, historicalTime, hoursBack]);

  const filteredAlerts = alerts.filter(alert => {
    if (filter === 'ALL') return true;
    if (filter === 'CRITICAL') return alert.priority === 'HIGH';
    if (filter === 'FLOW') return alert.type?.includes('Options') || alert.type?.includes('Block');
    if (filter === 'NEWS') return alert.type?.includes('Earnings') || alert.type?.includes('FDA');
    return true;
  });

  return (
    <div className="bg-slate-900 rounded-lg border border-slate-800 h-[calc(100vh-180px)] flex flex-col">
      {/* Header */}
      <div className="p-4 border-b border-slate-800 space-y-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Bell className="w-5 h-5 text-blue-400" />
            <h3 className="font-semibold text-slate-100">
              {useHistorical ? 'Historical Alerts' : 'Live Alerts'}
            </h3>
          </div>
          <div className="flex items-center gap-2">
            {!useHistorical && (
              <Badge variant={wsConnected ? 'success' : 'destructive'} className="text-xs">
                {wsConnected ? '🟢 Live' : '🔴 Offline'}
              </Badge>
            )}
            <Badge variant="outline" className="text-xs">
              {alerts.length} active
            </Badge>
          </div>
        </div>
        
        {/* Historical Data Toggle */}
        <div className="flex items-center gap-4 pt-2 border-t border-slate-800">
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={useHistorical}
              onChange={(e) => setUseHistorical(e.target.checked)}
              className="w-4 h-4"
            />
            <span className="text-sm text-slate-300">View Historical Data</span>
          </label>
          
          {useHistorical && (
            <div className="flex items-center gap-2">
              <Calendar className="w-4 h-4 text-slate-400" />
              <Input
                type="date"
                value={historicalDate}
                onChange={(e) => setHistoricalDate(e.target.value)}
                className="w-40"
                max={new Date().toISOString().split('T')[0]}
              />
              <Clock className="w-4 h-4 text-slate-400 ml-2" />
              <Input
                type="time"
                value={historicalTime}
                onChange={(e) => setHistoricalTime(e.target.value)}
                className="w-32"
                step="1"
              />
              <label className="text-xs text-slate-400 ml-2">Hours back:</label>
              <Input
                type="number"
                value={hoursBack}
                onChange={(e) => setHoursBack(parseInt(e.target.value) || 4)}
                className="w-20"
                min="1"
                max="24"
              />
            </div>
          )}
        </div>

        {/* Filters */}
        <div className="flex gap-2">
          {['ALL', 'CRITICAL', 'FLOW', 'NEWS'].map(f => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-2 py-1 rounded text-xs font-medium transition-colors ${
                filter === f
                  ? 'bg-blue-600 text-white'
                  : 'bg-slate-800 text-slate-400 hover:bg-slate-700'
              }`}
            >
              {f}
            </button>
          ))}
        </div>
      </div>

      {/* Alert List */}
      <div className="flex-1 overflow-y-auto p-4 space-y-3">
        {filteredAlerts.length === 0 ? (
          <div className="text-center text-slate-400 py-8">
            {wsConnected ? 'No alerts found. Waiting for real-time updates...' : '🔴 Offline - Waiting for connection...'}
          </div>
        ) : (
          filteredAlerts.map((alert, idx) => (
            <AlertCard key={idx} alert={alert} />
          ))
        )}
      </div>
    </div>
  );
}

function AlertCard({ alert }) {
  const getIcon = () => {
    if (alert.type?.includes('High') || alert.sentiment === 'BULLISH') {
      return <TrendingUp className="w-4 h-4 text-green-400" />;
    }
    if (alert.type?.includes('Low') || alert.sentiment === 'BEARISH') {
      return <TrendingDown className="w-4 h-4 text-red-400" />;
    }
    return <AlertTriangle className="w-4 h-4 text-yellow-400" />;
  };

  const getBorderColor = () => {
    if (alert.priority === 'HIGH') return 'border-l-red-500';
    if (alert.priority === 'MEDIUM') return 'border-l-yellow-500';
    return 'border-l-slate-700';
  };

  return (
    <div
      className={`p-3 bg-slate-800/50 rounded border-l-4 ${getBorderColor()} hover:bg-slate-800 transition-colors cursor-pointer`}
    >
      <div className="flex items-start gap-3">
        <div className="mt-0.5">{getIcon()}</div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <span className="font-semibold text-sm text-slate-100">
              {alert.symbol}
            </span>
            <Badge variant="secondary" className="text-xs">
              {alert.type || 'Alert'}
            </Badge>
          </div>
          <p className="text-xs text-slate-400 line-clamp-2">
            {alert.message || 'No message available'}
          </p>
          <div className="flex items-center justify-between mt-2">
            <span className="text-xs text-slate-500">
              {alert.timestamp ? new Date(alert.timestamp).toLocaleTimeString() : 'Unknown time'}
            </span>
            {alert.price && (
              <span className="text-xs font-semibold text-blue-400">
                ${parseFloat(alert.price).toFixed(2)}
              </span>
            )}
            {alert.premium && (
              <span className="text-xs font-semibold text-blue-400">
                ${(alert.premium / 1000).toFixed(0)}K
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
