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);
  const isMobile = window.innerWidth < 768;

  return (
    <>
      {/* Backdrop - Only on mobile */}
      {isMobile && (
        <div
          className="fixed inset-0 z-[9998] bg-black/50 backdrop-blur-sm transition-all duration-300"
          onClick={onClose}
          aria-hidden="true"
        />
      )}

      {/* Panel */}
      <div
        className={clsx(
          "fixed z-[9999] bg-[var(--bg-primary)] border border-[var(--border-primary)] shadow-2xl flex flex-col transition-all duration-300 ease-out",
          isMobile
            ? "inset-x-0 bottom-0 rounded-t-2xl max-h-[85vh]"
            : "right-0 top-full mt-2 w-96 max-w-sm rounded-xl shadow-xl max-h-96",
          className
        )}
      >
        {/* Mobile Handle */}
        {isMobile && (
          <div className="flex justify-center py-3">
            <div className="w-10 h-1 bg-[var(--border-secondary)] rounded-full" />
          </div>
        )}

        {/* Header */}
        <div className={`flex items-center justify-between border-b border-[var(--border-primary)] ${
          isMobile ? 'px-6 py-4' : 'px-4 py-3'
        }`}>
          <div className="flex items-center gap-2">
            <h3 className={`font-semibold text-[var(--text-primary)] ${
              isMobile ? 'text-lg' : 'text-sm'
            }`}>
              Notificaciones
            </h3>
            {unreadNotifications.length > 0 && (
              <Badge variant="info" size={isMobile ? "md" : "sm"}>
                {unreadNotifications.length} nuevas
              </Badge>
            )}
          </div>

          <div className="flex items-center gap-2">
            {unreadNotifications.length > 0 && (
              <Button
                variant="ghost"
                size={isMobile ? "md" : "sm"}
                onClick={onMarkAllAsRead}
                className={`${isMobile ? 'px-3 py-2 text-sm' : 'h-6 px-2 text-xs'}`}
              >
                <Check className={`${isMobile ? 'w-4 h-4 mr-2' : 'w-3 h-3 mr-1'}`} />
                Marcar todas
              </Button>
            )}
            <Button
              variant="ghost"
              size={isMobile ? "md" : "sm"}
              onClick={onClose}
              className={`${isMobile ? 'p-2' : 'h-6 w-6 p-0'} hover:bg-[var(--bg-secondary)] rounded-full`}
            >
              <X className={`${isMobile ? 'w-5 h-5' : 'w-3 h-3'}`} />
            </Button>
          </div>
        </div>

        {/* Notifications List */}
        <div className={`flex-1 overflow-y-auto ${isMobile ? 'px-2 py-2' : ''}`}>
          {notifications.length === 0 ? (
            <div className={`text-center ${isMobile ? 'py-12 px-6' : 'p-8'}`}>
              <CheckCircle className={`mx-auto mb-3 ${isMobile ? 'w-12 h-12' : 'w-8 h-8'}`} style={{ color: 'var(--color-success)' }} />
              <p className={`text-[var(--text-secondary)] ${isMobile ? 'text-base' : 'text-sm'}`}>
                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(
                      "transition-colors hover:bg-[var(--bg-secondary)] active:bg-[var(--bg-tertiary)]",
                      isMobile ? 'px-4 py-4 mx-2 my-1 rounded-lg' : 'p-3',
                      !notification.read && "bg-[var(--color-info)]/5"
                    )}
                  >
                    <div className={`flex gap-${isMobile ? '4' : '3'}`}>
                      {/* Icon */}
                      <div
                        className={`flex-shrink-0 rounded-full mt-0.5 ${isMobile ? 'p-2' : 'p-1'}`}
                        style={{ backgroundColor: getSeverityColor(notification.severity) + '15' }}
                      >
                        <SeverityIcon
                          className={`${isMobile ? 'w-5 h-5' : '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 ${isMobile ? 'mb-2' : 'mb-1'}`}>
                          <div className={`flex items-center gap-2 ${isMobile ? 'flex-wrap' : ''}`}>
                            <Badge variant={getSeverityBadge(notification.severity)} size={isMobile ? "md" : "sm"}>
                              {notification.severity.toUpperCase()}
                            </Badge>
                            <Badge variant="secondary" size={isMobile ? "md" : "sm"}>
                              {notification.item_type === 'alert' ? 'Alerta' : 'Recomendación'}
                            </Badge>
                          </div>
                          <span className={`font-medium text-[var(--text-secondary)] ${isMobile ? 'text-sm' : 'text-xs'}`}>
                            {formatTimestamp(notification.timestamp)}
                          </span>
                        </div>

                        {/* Title */}
                        <p className={`font-medium leading-tight text-[var(--text-primary)] ${
                          isMobile ? 'text-base mb-2' : 'text-sm mb-1'
                        }`}>
                          {notification.title}
                        </p>

                        {/* Message */}
                        <p className={`leading-relaxed text-[var(--text-secondary)] ${
                          isMobile ? 'text-sm mb-4' : 'text-xs mb-2'
                        }`}>
                          {notification.message}
                        </p>

                        {/* Actions */}
                        <div className={`flex items-center gap-2 ${isMobile ? 'flex-col sm:flex-row' : ''}`}>
                          {!notification.read && (
                            <Button
                              variant="ghost"
                              size={isMobile ? "md" : "sm"}
                              onClick={() => onMarkAsRead(notification.id)}
                              className={`${isMobile ? 'w-full sm:w-auto px-4 py-2 text-sm' : 'h-6 px-2 text-xs'}`}
                            >
                              <Check className={`${isMobile ? 'w-4 h-4 mr-2' : 'w-3 h-3 mr-1'}`} />
                              Marcar como leído
                            </Button>
                          )}
                          <Button
                            variant="ghost"
                            size={isMobile ? "md" : "sm"}
                            onClick={() => onRemoveNotification(notification.id)}
                            className={`text-[var(--color-error)] hover:text-[var(--color-error-dark)] ${
                              isMobile ? 'w-full sm:w-auto px-4 py-2 text-sm' : 'h-6 px-2 text-xs'
                            }`}
                          >
                            <Trash2 className={`${isMobile ? 'w-4 h-4 mr-2' : 'w-3 h-3 mr-1'}`} />
                            Eliminar
                          </Button>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer */}
        {notifications.length > 0 && (
          <div className={`border-t border-[var(--border-primary)] bg-[var(--bg-secondary)] ${
            isMobile ? 'px-6 py-4' : 'p-3'
          }`}>
            <Button
              variant="ghost"
              size={isMobile ? "md" : "sm"}
              onClick={onClearAll}
              className={`w-full text-[var(--color-error)] hover:text-[var(--color-error-dark)] ${
                isMobile ? 'px-4 py-3 text-sm' : 'text-xs'
              }`}
            >
              <Trash2 className={`${isMobile ? 'w-4 h-4 mr-2' : 'w-3 h-3 mr-1'}`} />
              Limpiar todas las notificaciones
            </Button>
          </div>
        )}
      </div>
    </>
  );
};