import { useEffect, useState } from 'react';
import {
  Bell,
  AlertTriangle,
  TrendingUp,
  TrendingDown,
  Zap,
  Shield,
  Calendar,
  X,
} from 'lucide-react';
import type { AlertsData, Alert, AlertType, AlertSeverity } from '@/types';
import { newsApi } from '@/services/api';

export default function AlertsPanel() {
  const [alertsData, setAlertsData] = useState<AlertsData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [filter, setFilter] = useState<'ALL' | AlertSeverity>('ALL');

  const loadAlerts = async () => {
    try {
      setIsLoading(true);
      const data = await newsApi.getAlerts(50);
      setAlertsData(data);
    } catch (error) {
      console.error('Error loading alerts:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadAlerts();

    // Auto-refresh every minute
    const interval = setInterval(loadAlerts, 60000);
    return () => clearInterval(interval);
  }, []);

  const filteredAlerts = alertsData?.alerts.filter(
    (alert) => filter === 'ALL' || alert.severity === filter
  ) || [];

  return (
    <div className="card">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="relative">
            <Bell className="w-6 h-6 text-yellow-500" />
            {alertsData && alertsData.critical_count > 0 && (
              <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-4 h-4 flex items-center justify-center">
                {alertsData.critical_count}
              </span>
            )}
          </div>
          <div>
            <h3 className="text-lg font-semibold">Alerts</h3>
            {alertsData && (
              <p className="text-xs text-gray-400">
                {alertsData.alerts.length} alerts • {alertsData.critical_count} critical
              </p>
            )}
          </div>
        </div>
      </div>

      <div className="mb-4">
        <div className="grid grid-cols-5 gap-2 text-sm">
          <button
            onClick={() => setFilter('ALL')}
            className={`px-2 py-1 rounded-md transition-colors ${
              filter === 'ALL' ? 'bg-blue-600' : 'bg-dark-bg hover:bg-dark-hover'
            }`}
          >
            All
          </button>
          <button
            onClick={() => setFilter('CRITICAL')}
            className={`px-2 py-1 rounded-md transition-colors ${
              filter === 'CRITICAL' ? 'bg-red-600' : 'bg-dark-bg hover:bg-dark-hover'
            }`}
          >
            Critical
          </button>
          <button
            onClick={() => setFilter('HIGH')}
            className={`px-2 py-1 rounded-md transition-colors ${
              filter === 'HIGH' ? 'bg-orange-600' : 'bg-dark-bg hover:bg-dark-hover'
            }`}
          >
            High
          </button>
          <button
            onClick={() => setFilter('MEDIUM')}
            className={`px-2 py-1 rounded-md transition-colors ${
              filter === 'MEDIUM' ? 'bg-yellow-600' : 'bg-dark-bg hover:bg-dark-hover'
            }`}
          >
            Medium
          </button>
          <button
            onClick={() => setFilter('LOW')}
            className={`px-2 py-1 rounded-md transition-colors ${
              filter === 'LOW' ? 'bg-gray-600' : 'bg-dark-bg hover:bg-dark-hover'
            }`}
          >
            Low
          </button>
        </div>
      </div>

      <div className="space-y-2 max-h-80 overflow-y-auto">
        {isLoading ? (
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-yellow-500"></div>
          </div>
        ) : filteredAlerts.length > 0 ? (
          filteredAlerts.map((alert) => (
            <AlertCard key={alert.id} alert={alert} />
          ))
        ) : (
          <p className="text-center text-gray-400 py-8">No alerts to display</p>
        )}
      </div>
    </div>
  );
}

function AlertCard({ alert }: { alert: Alert }) {
  const getAlertIcon = (type: AlertType) => {
    switch (type) {
      case 'PRICE_SPIKE':
        return <TrendingUp className="w-5 h-5 text-green-500" />;
      case 'PRICE_DROP':
        return <TrendingDown className="w-5 h-5 text-red-500" />;
      case 'NEWS_BREAKING':
        return <Zap className="w-5 h-5 text-blue-500" />;
      case 'SUPPORT_BREACH':
      case 'RESISTANCE_BREACH':
        return <Shield className="w-5 h-5 text-orange-500" />;
      case 'HIGH_VOLATILITY':
        return <AlertTriangle className="w-5 h-5 text-yellow-500" />;
      case 'ECONOMIC_EVENT':
        return <Calendar className="w-5 h-5 text-purple-500" />;
      default:
        return <Bell className="w-5 h-5 text-gray-500" />;
    }
  };

  const getSeverityColor = (severity: AlertSeverity) => {
    switch (severity) {
      case 'CRITICAL':
        return 'bg-red-500/20 border-red-500';
      case 'HIGH':
        return 'bg-orange-500/20 border-orange-500';
      case 'MEDIUM':
        return 'bg-yellow-500/20 border-yellow-500';
      case 'LOW':
        return 'bg-blue-500/20 border-blue-500';
    }
  };

  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffSecs = Math.floor(diffMs / 1000);
    const diffMins = Math.floor(diffMs / 60000);

    if (diffSecs < 60) {
      return `${diffSecs}s ago`;
    } else if (diffMins < 60) {
      return `${diffMins}m ago`;
    } else {
      return date.toLocaleTimeString();
    }
  };

  return (
    <div
      className={`p-3 rounded-md border-l-4 ${getSeverityColor(
        alert.severity
      )} hover:bg-dark-hover transition-colors`}
    >
      <div className="flex items-start gap-3">
        {getAlertIcon(alert.type)}
        <div className="flex-1 min-w-0">
          <div className="flex items-center justify-between mb-1">
            <h4 className="font-semibold text-sm">{alert.title}</h4>
            <span className="text-xs text-gray-500">{formatTime(alert.timestamp)}</span>
          </div>
          <p className="text-xs text-gray-400 mb-2">{alert.message}</p>
          <div className="flex items-center gap-2 flex-wrap">
            <span className={`text-xs px-2 py-0.5 rounded ${getSeverityColor(alert.severity)}`}>
              {alert.severity}
            </span>
            {alert.price && (
              <span className="text-xs px-2 py-0.5 rounded bg-dark-bg text-gray-400">
                ${alert.price.toFixed(2)}
              </span>
            )}
            {alert.change_percent && (
              <span
                className={`text-xs px-2 py-0.5 rounded ${
                  alert.change_percent > 0
                    ? 'bg-green-500/20 text-green-500'
                    : 'bg-red-500/20 text-red-500'
                }`}
              >
                {alert.change_percent > 0 ? '+' : ''}
                {alert.change_percent.toFixed(2)}%
              </span>
            )}
            {alert.action_required && (
              <span className="text-xs px-2 py-0.5 rounded bg-red-500/20 text-red-500 font-semibold">
                ACTION REQUIRED
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
