import { useEffect, useState } from 'react';
import { useWebSocket } from './useWebSocket';
import { useToast } from '@/hooks/use-toast';
import { useQueryClient } from '@tanstack/react-query';

export interface OrderNotification {
  id: string;
  orderId: string;
  type: 'status_change' | 'new_order' | 'assignment' | 'location_update';
  title: string;
  message: string;
  timestamp: Date;
  read: boolean;
}

export function useOrderUpdates() {
  const { isConnected, subscribe, unsubscribe } = useWebSocket();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [notifications, setNotifications] = useState<OrderNotification[]>([]);

  useEffect(() => {
    if (!isConnected) return;

    // Handle order status changes
    const handleOrderStatusChange = (message: any) => {
      const { orderId, status, details } = message.data;
      
      // Show toast notification
      const statusMessages: Record<string, string> = {
        'PHARMACY_CONFIRMED': 'Votre commande a été confirmée par la pharmacie',
        'COURIER_ASSIGNED': 'Un livreur a été assigné à votre commande',
        'PICKED_UP': 'Votre commande a été récupérée',
        'IN_TRANSIT': 'Votre commande est en cours de livraison',
        'DELIVERED': 'Votre commande a été livrée',
        'CANCELLED': 'Votre commande a été annulée',
        'NO_PHARMACY_AVAILABLE': 'Aucune pharmacie disponible dans votre zone'
      };

      const title = statusMessages[status] || 'Mise à jour de commande';
      const description = details?.message || `Commande ${orderId.substring(0, 8)} mise à jour`;

      toast({
        title,
        description,
        duration: 5000,
      });

      // Add to notifications
      const notification: OrderNotification = {
        id: Math.random().toString(36),
        orderId,
        type: 'status_change',
        title,
        message: description,
        timestamp: new Date(),
        read: false
      };

      setNotifications(prev => [notification, ...prev.slice(0, 49)]); // Keep last 50

      // Invalidate relevant queries
      queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
      queryClient.invalidateQueries({ queryKey: [`/api/orders/${orderId}`] });
    };

    // Handle new orders (for pharmacies)
    const handleNewOrder = (message: any) => {
      const orderData = message.data;
      
      toast({
        title: "Nouvelle commande",
        description: `Médicament: ${orderData.medicineName}`,
        duration: 10000, // Longer duration for new orders
      });

      const notification: OrderNotification = {
        id: Math.random().toString(36),
        orderId: orderData.id,
        type: 'new_order',
        title: 'Nouvelle commande',
        message: `Commande de ${orderData.medicineName} (${orderData.quantity}x)`,
        timestamp: new Date(),
        read: false
      };

      setNotifications(prev => [notification, ...prev.slice(0, 49)]);

      // Invalidate orders query to show new order
      queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
    };

    // Handle courier location updates
    const handleCourierLocation = (message: any) => {
      const { courierId, location } = message.data;
      
      // Update any active order tracking with new courier location
      queryClient.setQueriesData(
        { queryKey: ['/api/orders'] },
        (oldData: any) => {
          if (!oldData) return oldData;
          
          return oldData.map((order: any) => {
            if (order.assignedCourierId === courierId) {
              return {
                ...order,
                courierLocation: location,
                lastLocationUpdate: new Date().toISOString()
              };
            }
            return order;
          });
        }
      );
    };

    // Subscribe to events
    subscribe('order_status_change', handleOrderStatusChange);
    subscribe('new_order', handleNewOrder);
    subscribe('courier_location', handleCourierLocation);

    // Cleanup
    return () => {
      unsubscribe('order_status_change', handleOrderStatusChange);
      unsubscribe('new_order', handleNewOrder);
      unsubscribe('courier_location', handleCourierLocation);
    };
  }, [isConnected, subscribe, unsubscribe, toast, queryClient]);

  const markAsRead = (notificationId: string) => {
    setNotifications(prev =>
      prev.map(notification =>
        notification.id === notificationId
          ? { ...notification, read: true }
          : notification
      )
    );
  };

  const markAllAsRead = () => {
    setNotifications(prev =>
      prev.map(notification => ({ ...notification, read: true }))
    );
  };

  const clearNotifications = () => {
    setNotifications([]);
  };

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

  return {
    notifications,
    unreadCount,
    markAsRead,
    markAllAsRead,
    clearNotifications
  };
}