import React from 'react';
import { clsx } from 'clsx';
import { Button } from '../Button';
import { Badge } from '../Badge';
import { NotificationData } from '../../../hooks/useNotifications';
import {
  Check,
  Trash2,
  AlertTriangle,
  AlertCircle,
  Info,
  CheckCircle,
  X
} from 'lucide-react';

export interface NotificationPanelProps {
  notifications: NotificationData[];
  isOpen: boolean;
  onClose: () => void;
  onMarkAsRead: (id: string) => void;
  onMarkAllAsRead: () => void;
  onRemoveNotification: (id: string) => void;
  onClearAll: () => void;
  className?: string;
}

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' });
};

export const NotificationPanel: React.FC<NotificationPanelProps> = ({
  notifications,
  isOpen,
  onClose,
  onMarkAsRead,
  onMarkAllAsRead,
  onRemoveNotification,
  onClearAll,
  className
}) => {
  if (!isOpen) return null;

  const unreadNotifications = notifications.filter(n => !n.read);

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 z-40 bg-black/20"
        onClick={onClose}
        aria-hidden="true"
      />

      {/* Panel */}
      <div
        className={clsx(
          "absolute right-0 top-full mt-2 w-96 max-w-sm bg-[var(--bg-primary)] border border-[var(--border-primary)] rounded-lg shadow-xl z-50 max-h-96 flex flex-col",
          className
        )}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-[var(--border-primary)]">
          <div className="flex items-center gap-2">
            <h3 className="font-semibold text-sm" style={{ color: 'var(--text-primary)' }}>
              Notificaciones
            </h3>
            {unreadNotifications.length > 0 && (
              <Badge variant="info" size="sm">
                {unreadNotifications.length} nuevas
              </Badge>
            )}
          </div>

          <div className="flex items-center gap-1">
            {unreadNotifications.length > 0 && (
              <Button
                variant="ghost"
                size="sm"
                onClick={onMarkAllAsRead}
                className="h-6 px-2 text-xs"
              >
                Marcar todas
              </Button>
            )}
            <Button
              variant="ghost"
              size="sm"
              onClick={onClose}
              className="h-6 w-6 p-0"
            >
              <X className="h-3 w-3" />
            </Button>
          </div>
        </div>

        {/* Notifications List */}
        <div className="flex-1 overflow-y-auto">
          {notifications.length === 0 ? (
            <div className="p-8 text-center">
              <CheckCircle className="w-8 h-8 mx-auto mb-2" style={{ color: 'var(--color-success)' }} />
              <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
                No hay notificaciones
              </p>
            </div>
          ) : (
            <div className="divide-y divide-[var(--border-primary)]">
              {notifications.map((notification) => {
                const SeverityIcon = getSeverityIcon(notification.severity);

                return (
                  <div
                    key={notification.id}
                    className={clsx(
                      "p-3 hover:bg-[var(--bg-secondary)] transition-colors",
                      !notification.read && "bg-[var(--color-info)]/5"
                    )}
                  >
                    <div className="flex gap-3">
                      {/* Icon */}
                      <div
                        className="flex-shrink-0 p-1 rounded-full mt-0.5"
                        style={{ backgroundColor: getSeverityColor(notification.severity) + '15' }}
                      >
                        <SeverityIcon
                          className="w-3 h-3"
                          style={{ color: getSeverityColor(notification.severity) }}
                        />
                      </div>

                      {/* Content */}
                      <div className="flex-1 min-w-0">
                        {/* Header */}
                        <div className="flex items-start justify-between gap-2 mb-1">
                          <div className="flex items-center gap-2">
                            <Badge variant={getSeverityBadge(notification.severity)} size="sm">
                              {notification.severity.toUpperCase()}
                            </Badge>
                            <Badge variant="secondary" size="sm">
                              {notification.item_type === 'alert' ? 'Alerta' : 'Recomendación'}
                            </Badge>
                          </div>
                          <span className="text-xs font-medium" style={{ color: 'var(--text-secondary)' }}>
                            {formatTimestamp(notification.timestamp)}
                          </span>
                        </div>

                        {/* Title */}
                        <p className="text-sm font-medium mb-1 leading-tight" style={{ color: 'var(--text-primary)' }}>
                          {notification.title}
                        </p>

                        {/* Message */}
                        <p className="text-xs leading-relaxed mb-2" style={{ color: 'var(--text-secondary)' }}>
                          {notification.message}
                        </p>

                        {/* Actions */}
                        <div className="flex items-center gap-1">
                          {!notification.read && (
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => onMarkAsRead(notification.id)}
                              className="h-6 px-2 text-xs"
                            >
                              <Check className="w-3 h-3 mr-1" />
                              Marcar como leído
                            </Button>
                          )}
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => onRemoveNotification(notification.id)}
                            className="h-6 px-2 text-xs text-red-600 hover:text-red-700"
                          >
                            <Trash2 className="w-3 h-3 mr-1" />
                            Eliminar
                          </Button>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer */}
        {notifications.length > 0 && (
          <div className="p-3 border-t border-[var(--border-primary)] bg-[var(--bg-secondary)]">
            <Button
              variant="ghost"
              size="sm"
              onClick={onClearAll}
              className="w-full text-xs text-red-600 hover:text-red-700"
            >
              Limpiar todas las notificaciones
            </Button>
          </div>
        )}
      </div>
    </>
  );
};