import { useState } from 'react';
import { useRealTimeTracking } from '@/hooks/useRealTimeTracking';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Bell,
  BellRing,
  Clock,
  Package,
  AlertTriangle,
  Check,
  CheckCheck,
  Trash2,
  X
} from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { fr } from 'date-fns/locale';

interface NotificationCenterProps {
  variant?: 'dropdown' | 'panel';
  className?: string;
}

export function NotificationCenter({ variant = 'dropdown', className = '' }: NotificationCenterProps) {
  const {
    notifications,
    unreadCount,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    clearNotifications,
    getNotificationsByPriority
  } = useRealTimeTracking();

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

  const getNotificationIcon = (type: string, priority: string) => {
    if (priority === 'urgent') return <AlertTriangle className="h-4 w-4 text-red-500" />;
    
    switch (type) {
      case 'new_order':
        return <Package className="h-4 w-4 text-blue-500" />;
      case 'status_change':
        return <Bell className="h-4 w-4 text-green-500" />;
      case 'location_update':
        return <Clock className="h-4 w-4 text-orange-500" />;
      case 'system_alert':
        return <AlertTriangle className="h-4 w-4 text-yellow-500" />;
      default:
        return <Bell className="h-4 w-4 text-gray-500" />;
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'urgent': return 'border-l-red-500';
      case 'high': return 'border-l-orange-500';
      case 'medium': return 'border-l-blue-500';
      case 'low': return 'border-l-gray-500';
      default: return 'border-l-gray-300';
    }
  };

  const NotificationList = () => (
    <div className="space-y-2" data-testid="notification-list">
      {notifications.length === 0 ? (
        <div className="text-center py-8">
          <Bell className="h-12 w-12 text-gray-300 mx-auto mb-2" />
          <p className="text-gray-500">Aucune notification</p>
        </div>
      ) : (
        notifications.map((notification) => (
          <div
            key={notification.id}
            className={`p-3 rounded-lg border-l-4 transition-colors cursor-pointer ${
              notification.read ? 'bg-gray-50' : 'bg-blue-50'
            } ${getPriorityColor(notification.priority)} hover:bg-gray-100`}
            onClick={() => markNotificationAsRead(notification.id)}
            data-testid={`notification-${notification.id}`}
          >
            <div className="flex items-start gap-3">
              {getNotificationIcon(notification.type, notification.priority)}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-1">
                  <h4 className={`font-medium text-sm truncate ${
                    notification.read ? 'text-gray-700' : 'text-gray-900'
                  }`}>
                    {notification.title}
                  </h4>
                  {!notification.read && (
                    <div className="h-2 w-2 bg-blue-500 rounded-full flex-shrink-0" />
                  )}
                </div>
                <p className={`text-sm ${
                  notification.read ? 'text-gray-500' : 'text-gray-700'
                }`}>
                  {notification.message}
                </p>
                <p className="text-xs text-gray-400 mt-1">
                  {formatDistanceToNow(notification.timestamp, { 
                    addSuffix: true, 
                    locale: fr 
                  })}
                </p>
              </div>
            </div>
          </div>
        ))
      )}
    </div>
  );

  const ActionButtons = () => (
    <div className="flex items-center gap-2 pt-2">
      {unreadCount > 0 && (
        <Button
          variant="outline"
          size="sm"
          onClick={markAllNotificationsAsRead}
          className="flex items-center gap-1"
          data-testid="mark-all-read"
        >
          <CheckCheck className="h-3 w-3" />
          Tout marquer lu
        </Button>
      )}
      {notifications.length > 0 && (
        <Button
          variant="outline"
          size="sm"
          onClick={clearNotifications}
          className="flex items-center gap-1 text-red-600 hover:text-red-700"
          data-testid="clear-notifications"
        >
          <Trash2 className="h-3 w-3" />
          Effacer tout
        </Button>
      )}
    </div>
  );

  if (variant === 'panel') {
    return (
      <Card className={className} data-testid="notification-panel">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <BellRing className="h-5 w-5" />
              Notifications
              {unreadCount > 0 && (
                <Badge variant="destructive" className="ml-2">
                  {unreadCount}
                </Badge>
              )}
            </CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          <ScrollArea className="h-96">
            <NotificationList />
          </ScrollArea>
          <Separator className="my-3" />
          <ActionButtons />
        </CardContent>
      </Card>
    );
  }

  return (
    <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
      <DropdownMenuTrigger asChild>
        <Button 
          variant="ghost" 
          size="sm" 
          className={`relative ${className}`}
          data-testid="notification-trigger"
        >
          <Bell className="h-5 w-5" />
          {unreadCount > 0 && (
            <Badge 
              variant="destructive" 
              className="absolute -top-1 -right-1 h-5 w-5 rounded-full p-0 flex items-center justify-center text-xs"
            >
              {unreadCount > 99 ? '99+' : unreadCount}
            </Badge>
          )}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent 
        align="end" 
        className="w-80 max-h-96"
        data-testid="notification-dropdown"
      >
        <div className="px-3 py-2">
          <div className="flex items-center justify-between">
            <h3 className="font-semibold">Notifications</h3>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsOpen(false)}
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
        </div>
        <DropdownMenuSeparator />
        
        <ScrollArea className="max-h-64">
          <div className="px-1">
            <NotificationList />
          </div>
        </ScrollArea>
        
        {(unreadCount > 0 || notifications.length > 0) && (
          <>
            <DropdownMenuSeparator />
            <div className="px-3 py-2">
              <ActionButtons />
            </div>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

// Quick notification summary for dashboards
export function NotificationSummary() {
  const { notifications, unreadCount, getNotificationsByPriority } = useRealTimeTracking();
  
  const urgentNotifications = getNotificationsByPriority('urgent');
  const highNotifications = getNotificationsByPriority('high');
  
  if (notifications.length === 0) {
    return (
      <div className="text-center py-4">
        <Bell className="h-8 w-8 text-gray-300 mx-auto mb-2" />
        <p className="text-sm text-gray-500">Aucune notification récente</p>
      </div>
    );
  }

  return (
    <div className="space-y-3" data-testid="notification-summary">
      {urgentNotifications.length > 0 && (
        <div className="p-3 bg-red-50 border-l-4 border-red-500 rounded">
          <div className="flex items-center gap-2">
            <AlertTriangle className="h-4 w-4 text-red-500" />
            <span className="font-medium text-red-700">
              {urgentNotifications.length} notification(s) urgente(s)
            </span>
          </div>
        </div>
      )}
      
      {highNotifications.length > 0 && (
        <div className="p-3 bg-orange-50 border-l-4 border-orange-500 rounded">
          <div className="flex items-center gap-2">
            <BellRing className="h-4 w-4 text-orange-500" />
            <span className="font-medium text-orange-700">
              {highNotifications.length} notification(s) importante(s)
            </span>
          </div>
        </div>
      )}

      <div className="text-center">
        <p className="text-sm text-gray-600">
          {unreadCount} non lue(s) sur {notifications.length} total
        </p>
      </div>
    </div>
  );
}

// Live status indicator
export function LiveStatusIndicator() {
  const { isConnected } = useRealTimeTracking();
  
  return (
    <div className="flex items-center gap-2 text-xs" data-testid="live-status">
      <div 
        className={`h-2 w-2 rounded-full ${
          isConnected ? 'bg-green-400 animate-pulse' : 'bg-red-400'
        }`} 
      />
      <span className={isConnected ? 'text-green-600' : 'text-red-600'}>
        {isConnected ? 'Temps réel actif' : 'Déconnecté'}
      </span>
    </div>
  );
}