/**
 * Centre de notifications pour MediFlash SOS+
 * Interface utilisateur pour afficher et gérer les notifications temps réel
 */

import React, { useState } from 'react';
import { Bell, X, Clock, AlertTriangle, Info, CheckCircle, Volume2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { 
  Popover, 
  PopoverContent, 
  PopoverTrigger 
} from '@/components/ui/popover';
import { useNotifications, Notification, NotificationAction } from '@/hooks/useNotifications';
import { cn } from '@/lib/utils';

interface NotificationCenterProps {
  className?: string;
}

export function NotificationCenter({ className }: NotificationCenterProps) {
  const {
    notifications,
    unreadCount,
    isConnected,
    markAsRead,
    markAllAsRead,
    dismissNotification,
    executeNotificationAction,
    getCriticalNotifications
  } = useNotifications();

  const [isOpen, setIsOpen] = useState(false);
  const criticalNotifications = getCriticalNotifications();

  const getPriorityIcon = (priority: string) => {
    switch (priority) {
      case 'critical': return <AlertTriangle className="h-4 w-4 text-red-600" />;
      case 'high': return <AlertTriangle className="h-4 w-4 text-orange-600" />;
      case 'medium': return <Info className="h-4 w-4 text-blue-600" />;
      case 'low': return <Info className="h-4 w-4 text-gray-600" />;
      default: return <Info className="h-4 w-4 text-gray-600" />;
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'critical': return 'bg-red-50 border-red-200';
      case 'high': return 'bg-orange-50 border-orange-200';
      case 'medium': return 'bg-blue-50 border-blue-200';
      case 'low': return 'bg-gray-50 border-gray-200';
      default: return 'bg-gray-50 border-gray-200';
    }
  };

  const formatTimestamp = (timestamp: Date) => {
    const now = new Date();
    const diff = now.getTime() - timestamp.getTime();
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (days > 0) return `${days}j`;
    if (hours > 0) return `${hours}h`;
    if (minutes > 0) return `${minutes}min`;
    return 'À l\'instant';
  };

  const handleNotificationClick = (notification: Notification) => {
    if (!notification.readAt) {
      markAsRead(notification.id);
    }

    // Exécuter la première action disponible
    if (notification.actions && notification.actions.length > 0) {
      executeNotificationAction(notification.actions[0]);
    }
  };

  const handleActionClick = (action: NotificationAction, notification: Notification, event: React.MouseEvent) => {
    event.stopPropagation();
    executeNotificationAction(action);
    
    if (!notification.readAt) {
      markAsRead(notification.id);
    }
  };

  const handleDismiss = (notificationId: string, event: React.MouseEvent) => {
    event.stopPropagation();
    dismissNotification(notificationId);
  };

  return (
    <div className={className}>
      <Popover open={isOpen} onOpenChange={setIsOpen}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            size="sm"
            className="relative"
            data-testid="notification-trigger"
          >
            <Bell className="h-4 w-4" />
            
            {/* Badge de notifications non lues */}
            {unreadCount > 0 && (
              <Badge 
                className={cn(
                  "absolute -top-2 -right-2 h-5 w-5 p-0 flex items-center justify-center text-xs",
                  criticalNotifications.length > 0 
                    ? "bg-red-600 animate-pulse" 
                    : "bg-blue-600"
                )}
              >
                {unreadCount > 99 ? '99+' : unreadCount}
              </Badge>
            )}

            {/* Indicateur de connexion */}
            <div 
              className={cn(
                "absolute -bottom-1 -right-1 h-2 w-2 rounded-full",
                isConnected ? "bg-green-500" : "bg-red-500"
              )}
            />
          </Button>
        </PopoverTrigger>

        <PopoverContent className="w-96 p-0" align="end" side="bottom">
          <div className="flex items-center justify-between p-4 border-b">
            <div className="flex items-center gap-2">
              <h3 className="font-semibold">Notifications</h3>
              <Badge variant="secondary">{notifications.length}</Badge>
            </div>
            
            <div className="flex items-center gap-2">
              {unreadCount > 0 && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={markAllAsRead}
                  className="text-xs"
                >
                  Tout marquer lu
                </Button>
              )}
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsOpen(false)}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          </div>

          {/* Alertes critiques */}
          {criticalNotifications.length > 0 && (
            <div className="bg-red-50 border-b border-red-200 p-3">
              <div className="flex items-center gap-2 text-red-800">
                <Volume2 className="h-4 w-4 animate-pulse" />
                <span className="font-medium text-sm">
                  {criticalNotifications.length} urgence{criticalNotifications.length > 1 ? 's' : ''} médicale{criticalNotifications.length > 1 ? 's' : ''}
                </span>
              </div>
            </div>
          )}

          <ScrollArea className="h-96">
            {notifications.length === 0 ? (
              <div className="flex flex-col items-center justify-center p-8 text-center">
                <Bell className="h-12 w-12 text-gray-300 mb-3" />
                <p className="text-gray-600 font-medium">Aucune notification</p>
                <p className="text-gray-400 text-sm mt-1">
                  Les nouvelles notifications apparaîtront ici
                </p>
              </div>
            ) : (
              <div className="divide-y">
                {notifications.map((notification) => (
                  <NotificationItem
                    key={notification.id}
                    notification={notification}
                    onClick={() => handleNotificationClick(notification)}
                    onActionClick={handleActionClick}
                    onDismiss={handleDismiss}
                    formatTimestamp={formatTimestamp}
                    getPriorityIcon={getPriorityIcon}
                    getPriorityColor={getPriorityColor}
                  />
                ))}
              </div>
            )}
          </ScrollArea>

          {/* Footer */}
          <div className="border-t p-3 text-center">
            <div className="flex items-center justify-center gap-2 text-xs text-gray-500">
              <div 
                className={cn(
                  "h-2 w-2 rounded-full",
                  isConnected ? "bg-green-500" : "bg-red-500"
                )}
              />
              {isConnected ? 'Connecté aux notifications' : 'Déconnecté'}
            </div>
          </div>
        </PopoverContent>
      </Popover>
    </div>
  );
}

interface NotificationItemProps {
  notification: Notification;
  onClick: () => void;
  onActionClick: (action: NotificationAction, notification: Notification, event: React.MouseEvent) => void;
  onDismiss: (id: string, event: React.MouseEvent) => void;
  formatTimestamp: (timestamp: Date) => string;
  getPriorityIcon: (priority: string) => React.ReactNode;
  getPriorityColor: (priority: string) => string;
}

function NotificationItem({
  notification,
  onClick,
  onActionClick,
  onDismiss,
  formatTimestamp,
  getPriorityIcon,
  getPriorityColor
}: NotificationItemProps) {
  return (
    <Card 
      className={cn(
        "border-0 rounded-none cursor-pointer transition-colors hover:bg-gray-50",
        getPriorityColor(notification.priority),
        !notification.readAt && "bg-opacity-80"
      )}
      onClick={onClick}
      data-testid={`notification-${notification.id}`}
    >
      <CardContent className="p-4">
        <div className="flex items-start gap-3">
          {/* Icône de priorité */}
          <div className="flex-shrink-0 mt-0.5">
            {getPriorityIcon(notification.priority)}
          </div>

          {/* Contenu */}
          <div className="flex-1 min-w-0">
            <div className="flex items-start justify-between gap-2 mb-1">
              <h4 className={cn(
                "text-sm font-medium truncate",
                !notification.readAt && "font-semibold"
              )}>
                {notification.title}
              </h4>
              
              <div className="flex items-center gap-1 flex-shrink-0">
                <span className="text-xs text-gray-500">
                  {formatTimestamp(notification.timestamp)}
                </span>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100"
                  onClick={(e) => onDismiss(notification.id, e)}
                >
                  <X className="h-3 w-3" />
                </Button>
              </div>
            </div>

            <p className="text-sm text-gray-600 mb-2 leading-relaxed">
              {notification.message}
            </p>

            {/* Actions */}
            {notification.actions && notification.actions.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-3">
                {notification.actions.map((action) => (
                  <Button
                    key={action.id}
                    variant={action.action === 'api_call' ? 'default' : 'outline'}
                    size="sm"
                    className="h-7 text-xs"
                    onClick={(e) => onActionClick(action, notification, e)}
                    data-testid={`notification-action-${action.id}`}
                  >
                    {action.label}
                  </Button>
                ))}
              </div>
            )}

            {/* Indicateur non lu */}
            {!notification.readAt && (
              <div className="absolute top-2 left-2 h-2 w-2 bg-blue-600 rounded-full" />
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

export default NotificationCenter;