import { useState, useEffect, useCallback } from 'react';
// import { useWebSocket } from './useWebSocket'; // TODO: Fix WebSocket hook
import { useQueryClient } from '@tanstack/react-query';
import { useToast } from '@/hooks/use-toast';

export interface TrackingData {
  orderId: string;
  status: string;
  courierLocation?: { lat: number; lng: number };
  estimatedArrival?: Date;
  lastUpdate: Date;
}

export interface LiveNotification {
  id: string;
  type: 'status_change' | 'location_update' | 'new_order' | 'system_alert';
  title: string;
  message: string;
  data?: any;
  timestamp: Date;
  read: boolean;
  priority: 'low' | 'medium' | 'high' | 'urgent';
}

export function useRealTimeTracking(orderId?: string) {
  // TODO: Fix WebSocket hooks when available
  const isConnected = false;
  const subscribe = (event: string, handler: any) => {};
  const unsubscribe = (event: string, handler: any) => {};
  const send = (message: any) => {};
  const queryClient = useQueryClient();
  const { toast } = useToast();
  
  const [trackingData, setTrackingData] = useState<TrackingData | null>(null);
  const [notifications, setNotifications] = useState<LiveNotification[]>([]);
  const [isLiveTrackingEnabled, setIsLiveTrackingEnabled] = useState(false);

  // Handle order status changes
  const handleOrderStatusChange = useCallback((message: any) => {
    const { orderId: messageOrderId, status, details } = message;
    
    if (orderId && messageOrderId === orderId) {
      setTrackingData(prev => prev ? {
        ...prev,
        status,
        lastUpdate: new Date(),
        ...(details || {})
      } : null);

      // Show toast notification
      const statusMessages: Record<string, string> = {
        'PHARMACY_CONFIRMED': 'Commande confirmée par la pharmacie',
        'COURIER_ASSIGNED': 'Livreur assigné',
        'PICKED_UP': 'Commande récupérée',
        'IN_TRANSIT': 'En cours de livraison',
        'DELIVERED': 'Commande livrée',
        'CANCELLED': 'Commande annulée'
      };

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

      // Add to notifications
      const notification: LiveNotification = {
        id: Date.now().toString(),
        type: 'status_change',
        title,
        message: details?.message || `Statut mis à jour: ${status}`,
        data: { orderId: messageOrderId, status, details },
        timestamp: new Date(),
        read: false,
        priority: status === 'DELIVERED' ? 'high' : 'medium'
      };

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

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

  // Handle courier location updates
  const handleCourierLocation = useCallback((message: any) => {
    const { courierId, orderId: messageOrderId, location } = message;
    
    if (orderId && messageOrderId === orderId) {
      setTrackingData(prev => prev ? {
        ...prev,
        courierLocation: location,
        lastUpdate: new Date()
      } : null);

      // Update cache with new location
      queryClient.setQueryData([`/api/orders/${orderId}`], (oldData: any) => {
        if (!oldData) return oldData;
        return {
          ...oldData,
          courierLocation: location,
          lastLocationUpdate: new Date().toISOString()
        };
      });
    }
  }, [orderId, queryClient]);

  // Handle new orders (for pharmacies)
  const handleNewOrder = useCallback((message: any) => {
    const orderData = message.data;
    
    toast({
      title: "Nouvelle commande d'urgence",
      description: `${orderData.medicineName} (${orderData.quantity}x)`,
      duration: 10000,
    });

    const notification: LiveNotification = {
      id: Date.now().toString(),
      type: 'new_order',
      title: 'Nouvelle commande',
      message: `${orderData.medicineName} (${orderData.quantity}x)`,
      data: orderData,
      timestamp: new Date(),
      read: false,
      priority: 'urgent'
    };

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

    // Invalidate orders query
    queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
  }, [toast, queryClient]);

  // Handle system alerts
  const handleSystemAlert = useCallback((message: any) => {
    const { data: alertData } = message;
    
    toast({
      title: alertData.title,
      description: alertData.message,
      variant: alertData.priority === 'urgent' ? 'destructive' : 'default',
      duration: alertData.priority === 'urgent' ? 10000 : 5000,
    });

    const notification: LiveNotification = {
      id: Date.now().toString(),
      type: 'system_alert',
      title: alertData.title,
      message: alertData.message,
      data: alertData,
      timestamp: new Date(),
      read: false,
      priority: alertData.priority
    };

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

  // Subscribe to WebSocket events
  useEffect(() => {
    if (!isConnected) return;

    subscribe('order_status_change', handleOrderStatusChange);
    subscribe('courier_location', handleCourierLocation);
    subscribe('new_order', handleNewOrder);
    subscribe('system_alert', handleSystemAlert);

    return () => {
      unsubscribe('order_status_change', handleOrderStatusChange);
      unsubscribe('courier_location', handleCourierLocation);
      unsubscribe('new_order', handleNewOrder);
      unsubscribe('system_alert', handleSystemAlert);
    };
  }, [
    isConnected,
    subscribe,
    unsubscribe,
    handleOrderStatusChange,
    handleCourierLocation,
    handleNewOrder,
    handleSystemAlert
  ]);

  // Enable live tracking for specific order
  const enableLiveTracking = useCallback((orderIdToTrack: string) => {
    if (isConnected) {
      send({
        type: 'subscribe_order',
        orderId: orderIdToTrack
      });
      setIsLiveTrackingEnabled(true);
    }
  }, [isConnected, send]);

  // Send location update (for couriers)
  const sendLocationUpdate = useCallback((location: { lat: number; lng: number }) => {
    if (isConnected) {
      send({
        type: 'location_update',
        location,
        orderId
      });
    }
  }, [isConnected, send, orderId]);

  // Mark notification as read
  const markNotificationAsRead = useCallback((notificationId: string) => {
    setNotifications(prev =>
      prev.map(notification =>
        notification.id === notificationId
          ? { ...notification, read: true }
          : notification
      )
    );
  }, []);

  // Mark all notifications as read
  const markAllNotificationsAsRead = useCallback(() => {
    setNotifications(prev =>
      prev.map(notification => ({ ...notification, read: true }))
    );
  }, []);

  // Clear all notifications
  const clearNotifications = useCallback(() => {
    setNotifications([]);
  }, []);

  // Get unread notifications count
  const unreadCount = notifications.filter(n => !n.read).length;

  // Get notifications by priority
  const getNotificationsByPriority = useCallback((priority: LiveNotification['priority']) => {
    return notifications.filter(n => n.priority === priority);
  }, [notifications]);

  return {
    // Tracking data
    trackingData,
    isLiveTrackingEnabled,
    isConnected,
    
    // Notifications
    notifications,
    unreadCount,
    
    // Actions
    enableLiveTracking,
    sendLocationUpdate,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    clearNotifications,
    getNotificationsByPriority
  };
}