import React, { useState, useEffect } from 'react';
import { Card, CardHeader, CardBody } from '../../ui/Card';
import { Badge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import { useNotifications } from '../../../hooks/useNotifications';
import {
  AlertTriangle,
  AlertCircle,
  Info,
  CheckCircle,
  Clock,
  X,
  Wifi,
  WifiOff,
  Bell,
  ChevronDown,
  ChevronUp,
  Check,
  Trash2
} from 'lucide-react';

export interface Alert {
  id: string;
  item_type: 'alert' | 'recommendation';
  type: string;
  severity: 'urgent' | 'high' | 'medium' | 'low';
  title: string;
  message: string;
  timestamp: string;
  actions?: string[];
  metadata?: any;
  status?: 'active' | 'resolved' | 'acknowledged';
}

export interface RealTimeAlertsProps {
  className?: string;
  maxAlerts?: number;
}

const RealTimeAlerts: React.FC<RealTimeAlertsProps> = ({
  className,
  maxAlerts = 10
}) => {
  const [expandedAlert, setExpandedAlert] = useState<string | null>(null);

  const { notifications, isConnected, markAsRead, removeNotification } = useNotifications();

  // Convert notifications to alerts format and limit them
  const alerts = notifications.slice(0, maxAlerts).map(notification => ({
    id: notification.id,
    item_type: notification.item_type,
    type: notification.item_type, // Use item_type as type
    severity: notification.severity,
    title: notification.title,
    message: notification.message,
    timestamp: notification.timestamp,
    status: notification.read ? 'acknowledged' as const : 'active' as const,
  }));

  const getSeverityIcon = (severity: string) => {
    switch (severity) {
      case 'urgent':
        return AlertTriangle;
      case 'high':
        return AlertCircle;
      case 'medium':
        return Info;
      case 'low':
        return CheckCircle;
      default:
        return Info;
    }
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'urgent':
        return 'var(--color-error)';
      case 'high':
        return 'var(--color-warning)';
      case 'medium':
        return 'var(--color-info)';
      case 'low':
        return 'var(--color-success)';
      default:
        return 'var(--color-info)';
    }
  };

  const getSeverityBadge = (severity: string) => {
    switch (severity) {
      case 'urgent':
        return 'error';
      case 'high':
        return 'warning';
      case 'medium':
        return 'info';
      case 'low':
        return 'success';
      default:
        return 'info';
    }
  };

  const formatTimestamp = (timestamp: string) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));

    if (diffMins < 1) return 'Ahora';
    if (diffMins < 60) return `${diffMins}m`;
    const diffHours = Math.floor(diffMins / 60);
    if (diffHours < 24) return `${diffHours}h`;
    return date.toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' });
  };

  const toggleExpanded = (alertId: string) => {
    setExpandedAlert(prev => prev === alertId ? null : alertId);
  };

  const handleMarkAsRead = (alertId: string) => {
    markAsRead(alertId);
  };

  const handleRemoveAlert = (alertId: string) => {
    removeNotification(alertId);
    if (expandedAlert === alertId) {
      setExpandedAlert(null);
    }
  };

  const activeAlerts = alerts.filter(alert => alert.status === 'active');
  const urgentCount = activeAlerts.filter(alert => alert.severity === 'urgent').length;
  const highCount = activeAlerts.filter(alert => alert.severity === 'high').length;

  return (
    <Card className={className} variant="elevated" padding="none">
      <CardHeader padding="md" divider>
        <div className="flex items-center justify-between w-full">
          <div className="flex items-center gap-3">
            <div
              className="p-2 rounded-lg"
              style={{ backgroundColor: 'var(--color-primary)20' }}
            >
              <Bell className="w-4 h-4" style={{ color: 'var(--color-primary)' }} />
            </div>
            <div>
              <h3 className="text-base font-semibold" style={{ color: 'var(--text-primary)' }}>
                Alertas
              </h3>
              <div className="flex items-center gap-2">
                {isConnected ? (
                  <Wifi className="w-3 h-3" style={{ color: 'var(--color-success)' }} />
                ) : (
                  <WifiOff className="w-3 h-3" style={{ color: 'var(--color-error)' }} />
                )}
                <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>
                  {isConnected ? 'En vivo' : 'Desconectado'}
                </span>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-1">
            {urgentCount > 0 && (
              <Badge variant="error" size="sm">
                {urgentCount}
              </Badge>
            )}
            {highCount > 0 && (
              <Badge variant="warning" size="sm">
                {highCount}
              </Badge>
            )}
          </div>
        </div>
      </CardHeader>

      <CardBody padding="none">
        {activeAlerts.length === 0 ? (
          <div className="p-6 text-center">
            <CheckCircle className="w-6 h-6 mx-auto mb-2" style={{ color: 'var(--color-success)' }} />
            <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
              No hay alertas activas
            </p>
          </div>
        ) : (
          <div className="space-y-2 p-2">
            {activeAlerts.map((alert) => {
              const isExpanded = expandedAlert === alert.id;
              const SeverityIcon = getSeverityIcon(alert.severity);

              return (
                <div
                  key={alert.id}
                  className={`
                    rounded-lg border transition-all duration-200
                    ${isExpanded ? 'ring-2 ring-opacity-20' : 'hover:shadow-sm'}
                  `}
                  style={{
                    borderColor: getSeverityColor(alert.severity) + '40',
                    backgroundColor: 'var(--bg-primary)',
                    ...(isExpanded && {
                      ringColor: getSeverityColor(alert.severity),
                      backgroundColor: 'var(--bg-secondary)'
                    })
                  }}
                >
                  {/* Compact Card Header */}
                  <div
                    className="flex items-center gap-3 p-3 cursor-pointer hover:bg-[var(--bg-secondary)] transition-colors rounded-lg"
                    onClick={() => toggleExpanded(alert.id)}
                  >
                    {/* Severity Icon */}
                    <div
                      className="flex-shrink-0 p-2 rounded-full"
                      style={{ backgroundColor: getSeverityColor(alert.severity) + '15' }}
                    >
                      <SeverityIcon
                        className="w-4 h-4"
                        style={{ color: getSeverityColor(alert.severity) }}
                      />
                    </div>

                    {/* Alert Content */}
                    <div className="flex-1 min-w-0">
                      {/* Title and Timestamp Row */}
                      <div className="flex items-start justify-between gap-3 mb-2">
                        <h4 className="text-sm font-semibold leading-tight flex-1" style={{ color: 'var(--text-primary)' }}>
                          {alert.title}
                        </h4>
                        <span className="text-xs font-medium flex-shrink-0" style={{ color: 'var(--text-secondary)' }}>
                          {formatTimestamp(alert.timestamp)}
                        </span>
                      </div>

                      {/* Badges Row */}
                      <div className="flex items-center gap-2 mb-2">
                        <Badge variant={getSeverityBadge(alert.severity)} size="sm">
                          {alert.severity.toUpperCase()}
                        </Badge>
                        <Badge variant="secondary" size="sm">
                          {alert.item_type === 'alert' ? '🚨 Alerta' : '💡 Recomendación'}
                        </Badge>
                      </div>

                      {/* Preview message when collapsed */}
                      {!isExpanded && (
                        <p className="text-xs leading-relaxed truncate" style={{ color: 'var(--text-secondary)' }}>
                          {alert.message}
                        </p>
                      )}
                    </div>

                    {/* Expand/Collapse Button */}
                    <div className="flex-shrink-0 p-1 rounded-full hover:bg-black/5 transition-colors">
                      {isExpanded ? (
                        <ChevronUp className="w-4 h-4" style={{ color: 'var(--text-secondary)' }} />
                      ) : (
                        <ChevronDown className="w-4 h-4" style={{ color: 'var(--text-secondary)' }} />
                      )}
                    </div>
                  </div>

                  {/* Expanded Details */}
                  {isExpanded && (
                    <div className="px-3 pb-3 border-t mt-3 pt-3" style={{ borderColor: getSeverityColor(alert.severity) + '20' }}>
                      {/* Full Message */}
                      <div className="mb-4">
                        <p className="text-sm leading-relaxed" style={{ color: 'var(--text-primary)' }}>
                          {alert.message}
                        </p>
                      </div>

                      {/* Actions Section */}
                      {alert.actions && alert.actions.length > 0 && (
                        <div className="mb-4">
                          <p className="text-xs font-semibold mb-2 uppercase tracking-wide" style={{ color: 'var(--text-primary)' }}>
                            Acciones Recomendadas
                          </p>
                          <div className="space-y-1">
                            {alert.actions.map((action, index) => (
                              <div key={index} className="flex items-start gap-2">
                                <span className="text-xs mt-0.5" style={{ color: getSeverityColor(alert.severity) }}>
                                  •
                                </span>
                                <span className="text-xs leading-relaxed" style={{ color: 'var(--text-secondary)' }}>
                                  {action}
                                </span>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* Metadata */}
                      {alert.metadata && Object.keys(alert.metadata).length > 0 && (
                        <div className="mb-4 p-2 rounded-md" style={{ backgroundColor: 'var(--bg-secondary)' }}>
                          <p className="text-xs font-semibold mb-1 uppercase tracking-wide" style={{ color: 'var(--text-primary)' }}>
                            Detalles Adicionales
                          </p>
                          <div className="text-xs space-y-1" style={{ color: 'var(--text-secondary)' }}>
                            {Object.entries(alert.metadata).map(([key, value]) => (
                              <div key={key} className="flex gap-2">
                                <span className="font-medium capitalize">{key.replace(/_/g, ' ')}:</span>
                                <span>{String(value)}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* Action Buttons */}
                      <div className="flex items-center gap-2 pt-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleMarkAsRead(alert.id);
                          }}
                          className="h-8 px-3 text-xs font-medium"
                        >
                          <Check className="w-3 h-3 mr-1" />
                          Marcar como leído
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleRemoveAlert(alert.id);
                          }}
                          className="h-8 px-3 text-xs font-medium text-red-600 hover:text-red-700 hover:bg-red-50"
                        >
                          <Trash2 className="w-3 h-3 mr-1" />
                          Eliminar
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}

        {activeAlerts.length > 0 && (
          <div
            className="p-3 border-t text-center"
            style={{
              borderColor: 'var(--border-primary)',
              backgroundColor: 'var(--bg-secondary)'
            }}
          >
            <p className="text-xs" style={{ color: 'var(--text-secondary)' }}>
              {activeAlerts.length} alertas activas
            </p>
          </div>
        )}
      </CardBody>
    </Card>
  );
};

export default RealTimeAlerts;