Quiero que iteres en el siguiente archivo para encontrar errores, incosistencias, mejorar a aplicar y que funcione mejor: // GlobalContext.js

import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  useCallback,
  useMemo,
} from 'react';
import useSWR, { mutate } from 'swr';
import { useSocket } from './SocketContext';
import { useGeolocation } from '../hooks/useGeolocation';

const API_BASE_URL = 'http://localhost:3003';
export { API_BASE_URL };

// Creación del contexto global con valores iniciales
const GlobalContext = createContext({
  worker: null,
  workerLoading: true,
  workerDocuments: {
    vehicle: [],
    license: [],
    insurance: [],
    certification: [],
  },
  loading: false,
  error: null,
  auth: {
    admin: { user: null, loading: false, error: null },
    seller: { user: null, loading: false, error: null },
    worker: { user: null, loading: false, error: null },
  },
});

export const useGlobalContext = () => useContext(GlobalContext);

// Función para obtener el token de autenticación desde localStorage
const getToken = () => {
  const userTypes = ['admin', 'seller', 'worker'];
  for (const type of userTypes) {
    const storedUser = localStorage.getItem(`currentUser_${type}`);
    if (storedUser) {
      const { token } = JSON.parse(storedUser);
      if (token) {
        return token;
      }
    }
  }
  return null;
};

// Función fetcher personalizada para SWR
const fetcher = async (url, method = 'GET', body = null, params = {}) => {
  const headers = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
    ...(params.headers || {}),
  };

  const token = getToken();
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  // Asegurar que la URL comience con '/api'
  if (!url.startsWith('/api')) {
    url = '/api' + url;
  }

  let fullUrl = API_BASE_URL + url;

  // Añadir parámetros de consulta si existen
  if (params && Object.keys(params).length > 0) {
    const queryParams = { ...params };
    delete queryParams.headers;
    const queryString = new URLSearchParams(queryParams).toString();
    fullUrl += `?${queryString}`;
  }

  const response = await fetch(fullUrl, {
    method,
    headers,
    body: body ? JSON.stringify(body) : null,
  });

  if (!response.ok) {
    const errorData = await response.json();
    const error = new Error(errorData.message || 'Error en la solicitud');
    error.status = response.status;
    error.info = errorData;
    throw error;
  }

  return response.json();
};

// Provider global que utiliza SWR para la gestión de datos
export const GlobalProvider = ({ children }) => {
  const [auth, setAuth] = useState({
    admin: { user: null, loading: false, error: null },
    seller: { user: null, loading: false, error: null },
    worker: { user: null, loading: false, error: null },
  });

  const [error, setError] = useState(null);
  const [validationErrors, setValidationErrors] = useState({});
  const [notifications, setNotifications] = useState({
    proposals: 0,
    lastChecked: null,
  });

  const [currentStoreId, setCurrentStoreId] = useState(null);
  const [currentStore, setCurrentStore] = useState(null);
  const [storeSettings, setStoreSettings] = useState(null);

  const [worker, setWorker] = useState(null);
  const [workerLoading, setWorkerLoading] = useState(true);
  const [workerError, setWorkerError] = useState(null);
  const [workerStatus, setWorkerStatus] = useState({
    isAvailable: false,
    currentStatus: 'offline',
    lastUpdate: null,
  });
  const [workerProfile, setWorkerProfile] = useState(null);

  const [socketError, setSocketError] = useState(null);

  const { socket, isConnected, connectSocket, disconnectSocket } = useSocket();
  const { location } = useGeolocation();

  // Función para manejar errores generales
  const handleError = useCallback((error, customMessage) => {
    const errorMessage =
      error.info?.message || error.message || customMessage;
    console.error(customMessage, error);
    setError(errorMessage);
    return {
      success: false,
      message: errorMessage,
    };
  }, []);

  // ===========================
  // Hooks SWR Personalizados
  // ===========================

  // Hook para obtener estadísticas
  const useStats = (startDate, endDate) => {
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);

    const { data, error: swrError } = useSWR(
      ['/stats', startDate, endDate],
      async (url, start, end) => {
        try {
          const response = await fetcher(url, 'GET', null, { 
            startDate: start, 
            endDate: end 
          });
          return response.data;
        } catch (err) {
          throw new Error(err.message || 'Error al obtener estadísticas');
        }
      }
    );

    useEffect(() => {
      if (data || swrError) {
        setIsLoading(false);
      }
      if (swrError) {
        setError(swrError.message);
      }
    }, [data, swrError]);

    return {
      stats: data,
      isLoading,
      error
    };
  };

  // Hook para obtener alertas
  const useAlerts = () => {
    const { data, error } = useSWR('/api/alerts', fetcher);

    return {
      alerts: data,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener tiendas
  const useStores = () => {
    const { data, error } = useSWR('/api/stores', fetcher);

    return {
      stores: data,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener cooperativas
  const useCooperatives = () => {
    const { data, error } = useSWR('/api/cooperatives', fetcher);

    return {
      cooperatives: data,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener productos y servicios de una tienda
  const useProductsAndServices = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/products/${storeId}` : null,
      fetcher
    );

    return {
      products: data?.data?.products || [],
      services: data?.data?.services || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener usuarios con paginación y filtros
  const useUsers = (page = 1, limit = 10, filters = {}) => {
    const queryParams = new URLSearchParams({
      page,
      limit,
      ...filters,
      sortBy: filters.sortBy || 'createdAt',
      sortOrder: filters.sortOrder || -1,
    }).toString();

    const { data, error } = useSWR(`/api/users?${queryParams}`, fetcher);

    return {
      users: data?.users || [],
      totalUsers: data?.totalUsers || 0,
      totalPages: data?.totalPages || 1,
      currentPage: data?.currentPage || 1,
      hasMore: data?.hasMore || false,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener órdenes
  const useOrders = () => {
    const { data, error } = useSWR('/api/orders', fetcher);

    return {
      orders: data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener servicios
  const useServices = () => {
    const { data, error } = useSWR('/api/services', fetcher);

    return {
      services: data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener entregas activas
  const useActiveDeliveries = (workerId) => {
    const { data, error } = useSWR(
      workerId ? `/api/workers/${workerId}/active-deliveries` : null,
      fetcher
    );

    return {
      activeDeliveries: data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener la entrega actual
  const useCurrentDelivery = (workerId) => {
    const { data, error } = useSWR(
      workerId ? `/api/workers/${workerId}/current-delivery` : null,
      fetcher
    );

    return {
      currentDelivery: data || null,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener el dashboard del trabajador
  const useDashboardStats = (workerId) => {
    const { data, error } = useSWR(
      workerId ? `/api/workers/${workerId}/dashboard-stats` : null,
      fetcher
    );

    return {
      dashboardStats: data || null,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener las ganancias del trabajador
  const useWorkerEarnings = () => {
    const { data, error } = useSWR('/api/earnings', fetcher);

    return {
      workerEarnings: data?.data || { today: 0, week: 0, month: 0 },
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener el historial de entregas
  const useDeliveryHistory = () => {
    const { data, error } = useSWR('/api/deliveries/history', fetcher);

    return {
      deliveryHistory: data?.data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener documentos del trabajador
  const useWorkerDocuments = () => {
    const { data, error } = useSWR('/api/worker/documents', fetcher);

    return {
      workerDocuments: data?.data || {
        vehicle: [],
        license: [],
        insurance: [],
        certification: [],
      },
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener chats activos
  const useActiveChats = () => {
    const { data, error } = useSWR('/api/chat/active', fetcher);

    return {
      activeChats: data?.data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener métricas de entregas
  const useDeliveryMetrics = () => {
    const { data, error } = useSWR('/api/deliveries/metrics', fetcher);

    return {
      deliveryMetrics: data?.data || null,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener datos del dashboard del trabajador
  const useWorkerDashboard = (workerId) => {
    const { data, error } = useSWR(
      workerId ? `/api/worker/dashboard` : null,
      fetcher
    );

    return {
      workerDashboard: data || {
        dailyStats: { orders: 0, earnings: 0, distance: 0 },
        weeklyStats: { orders: 0, earnings: 0, distance: 0 },
        performanceMetrics: {
          rating: 0,
          completionRate: 0,
          avgDeliveryTime: 0,
          customerSatisfaction: 0,
        },
        availableOrders: [],
      },
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener rutas inteligentes
  const useSmartRoutes = () => {
    const { data, error } = useSWR('/api/routes', fetcher);

    return {
      smartRoutes: data || {
        activeOrders: [],
        optimizedRoute: null,
        trafficData: null,
        hotZones: [],
        timeSlots: [],
      },
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener las entregas de una tienda
  const useStoreDeliveries = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/${storeId}/deliveries` : null,
      fetcher
    );

    return {
      storeDeliveries: data?.data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener detalles de una tienda
  const useStoreDetails = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/details/${storeId}` : null,
      fetcher
    );

    return {
      storeDetails: data?.data || null,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener propuestas de venta al por mayor
  const useWholesaleProposals = (userId) => {
    const { data, error } = useSWR(
      userId ? `/api/proposals?userId=${userId}` : null,
      fetcher
    );

    return {
      wholesaleProposals: data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener productos de todas las tiendas
  const useAllProducts = (params) => {
    const queryParams = new URLSearchParams({
      page: params.page,
      limit: params.limit,
      search: params.search,
      store: params.filters.store,
      type: params.filters.type,
      status: params.filters.status,
      sortBy: params.sort?.key,
      sortDirection: params.sort?.direction,
    }).toString();

    const { data, error } = useSWR(`/api/products/list?${queryParams}`, fetcher);

    return {
      allProducts: data?.products || [],
      total: data?.total || 0,
      page: data?.page || 1,
      totalPages: data?.totalPages || 1,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener productos de una tienda
  const useStoreProducts = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/products/${storeId}` : null,
      fetcher
    );

    return {
      storeProducts: data?.data?.products || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener ventas de una tienda
  const useStoreSales = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/${storeId}/sales` : null,
      fetcher
    );

    return {
      storeSales: data?.data?.sales || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener el conteo de productos de una tienda
  const useStoreProductCount = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/${storeId}/products/count` : null,
      fetcher
    );

    return {
      productCount: data?.count || 0,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener el conteo de órdenes de una tienda
  const useStoreOrderCount = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/${storeId}/orders/count` : null,
      fetcher
    );

    return {
      orderCount: data?.count || 0,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // ===========================
  // Funciones de Mutación y Acciones
  // ===========================

  // Función para agregar una tienda
  const addStore = useCallback(async (storeData) => {
    try {
      const newStore = await fetcher('/api/stores', 'POST', storeData);
      mutate('/api/stores', (stores) => [...stores, newStore], false);
      return newStore;
    } catch (error) {
      return handleError(error, 'Error al crear la tienda');
    }
  }, [handleError]);

  // Función para actualizar una tienda
  const updateStore = useCallback(async (storeId, storeData) => {
    try {
      const updatedStore = await fetcher(
        `/api/stores/${storeId}`,
        'PUT',
        storeData
      );
      mutate('/api/stores', (stores) =>
        stores.map((store) => (store._id === storeId ? updatedStore : store))
      );
      return updatedStore;
    } catch (error) {
      return handleError(error, 'Error al actualizar la tienda');
    }
  }, [handleError]);

  // Función para eliminar una tienda
  const deleteStore = useCallback(async (storeId) => {
    try {
      await fetcher(`/api/stores/${storeId}`, 'DELETE');
      mutate('/api/stores', (stores) =>
        stores.filter((store) => store._id !== storeId)
      );
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar la tienda');
    }
  }, [handleError]);

  // Función para agregar una cooperativa
  const addCooperative = useCallback(async (cooperativeData) => {
    try {
      const newCoop = await fetcher(
        '/api/cooperatives',
        'POST',
        cooperativeData
      );
      mutate('/api/cooperatives', (cooperatives) => [...cooperatives, newCoop]);
      return newCoop;
    } catch (error) {
      return handleError(error, 'Error al crear la cooperativa');
    }
  }, [handleError]);

  // Función para actualizar una cooperativa
  const updateCooperative = useCallback(async (cooperativeId, cooperativeData) => {
    try {
      const updatedCoop = await fetcher(
        `/api/cooperatives/${cooperativeId}`,
        'PUT',
        cooperativeData
      );
      mutate('/api/cooperatives', (cooperatives) =>
        cooperatives.map((coop) =>
          coop._id === cooperativeId ? updatedCoop : coop
        )
      );
      return updatedCoop;
    } catch (error) {
      return handleError(error, 'Error al actualizar la cooperativa');
    }
  }, [handleError]);

  // Función para eliminar una cooperativa
  const deleteCooperative = useCallback(async (cooperativeId) => {
    try {
      await fetcher(`/api/cooperatives/${cooperativeId}`, 'DELETE');
      mutate('/api/cooperatives', (cooperatives) =>
        cooperatives.filter((coop) => coop._id !== cooperativeId)
      );
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar la cooperativa');
    }
  }, [handleError]);

  // Función para agregar un producto
  const addProduct = useCallback(async (productData) => {
    try {
      const newProduct = await fetcher('/api/products', 'POST', productData);
      mutate('/api/products/list', (data) => ({
        ...data,
        products: [...data.products, newProduct],
      }));
      return newProduct;
    } catch (error) {
      if (error.info?.errors) {
        setValidationErrors(error.info.errors);
      }
      return handleError(error, 'Error al crear el producto');
    }
  }, [handleError]);

  // Función para actualizar un producto
  const updateProduct = useCallback(async (productId, productData) => {
    try {
      const updatedProduct = await fetcher(
        `/api/products/${productId}`,
        'PUT',
        productData
      );
      mutate('/api/products/list', (data) => ({
        ...data,
        products: data.products.map((product) =>
          product._id === productId ? updatedProduct : product
        ),
      }));
      return updatedProduct;
    } catch (error) {
      return handleError(error, 'Error al actualizar el producto');
    }
  }, [handleError]);

  // Función para eliminar un producto
  const deleteProduct = useCallback(async (productId) => {
    try {
      await fetcher(`/api/products/${productId}`, 'DELETE');
      mutate('/api/products/list', (data) => ({
        ...data,
        products: data.products.filter((product) => product._id !== productId),
      }));
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar el producto');
    }
  }, [handleError]);

  // Función para agregar un servicio
  const addService = useCallback(async (serviceData) => {
    try {
      const newService = await fetcher('/api/services', 'POST', serviceData);
      mutate('/api/services', (services) => [...services, newService]);
      return newService;
    } catch (error) {
      return handleError(error, 'Error al crear el servicio');
    }
  }, [handleError]);

  // Función para actualizar un servicio
  const updateService = useCallback(async (serviceId, serviceData) => {
    try {
      const updatedService = await fetcher(
        `/api/services/${serviceId}`,
        'PUT',
        serviceData
      );
      mutate('/api/services', (services) =>
        services.map((service) =>
          service._id === serviceId ? updatedService : service
        )
      );
      return updatedService;
    } catch (error) {
      return handleError(error, 'Error al actualizar el servicio');
    }
  }, [handleError]);

  // Función para eliminar un servicio
  const deleteService = useCallback(async (serviceId) => {
    try {
      await fetcher(`/api/services/${serviceId}`, 'DELETE');
      mutate('/api/services', (services) =>
        services.filter((service) => service._id !== serviceId)
      );
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar el servicio');
    }
  }, [handleError]);

  // Función para agregar un usuario
  const addUser = useCallback(async (userData) => {
    try {
      const newUser = await fetcher('/api/users', 'POST', userData);
      mutate('/api/users', (users) => [...users, newUser]);
      return newUser;
    } catch (error) {
      return handleError(error, 'Error al agregar usuario');
    }
  }, [handleError]);

  // Función para actualizar un usuario
  const updateUser = useCallback(async (userId, userData) => {
    try {
      const updatedUser = await fetcher(
        `/api/users/${userId}`,
        'PATCH',
        userData
      );
      mutate('/api/users', (users) =>
        users.map((user) => (user._id === userId ? updatedUser : user))
      );
      return updatedUser;
    } catch (error) {
      return handleError(error, 'Error al actualizar el usuario');
    }
  }, [handleError]);

  // Función para eliminar un usuario
  const deleteUser = useCallback(async (userId) => {
    try {
      await fetcher(`/api/users/${userId}`, 'DELETE');
      mutate('/api/users', (users) =>
        users.filter((user) => user._id !== userId)
      );
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar el usuario');
    }
  }, [handleError]);

  // Función para actualizar el estado de una orden
  const updateOrderStatus = useCallback(
    async (orderId, newStatus, storeId = null) => {
      try {
        const updatedOrder = await fetcher(
          `/api/orders/${orderId}/status`,
          'PATCH',
          { status: newStatus, storeId }
        );
        mutate('/api/orders', (orders) =>
          orders.map((order) =>
            order._id === orderId ? { ...order, status: newStatus } : order
          )
        );
        return { success: true, data: updatedOrder };
      } catch (error) {
        return handleError(error, 'Error al actualizar el estado de la orden');
      }
    },
    [handleError]
  );

  // Función para actualizar el estado del trabajador
  const updateWorkerStatus = useCallback(
    async (newStatus) => {
      try {
        if (!worker) throw new Error('No autenticado');

        const workerId = worker._id;
        const locationData = location
          ? {
              type: 'Point',
              coordinates: [location.longitude, location.latitude],
            }
          : null;

        const updatedWorker = await fetcher(
          `/api/workers/${workerId}/status`,
          'PUT',
          {
            status: newStatus,
            location: locationData,
          }
        );

        mutate(`/api/workers/${workerId}`, updatedWorker, false);

        setWorker((prev) => ({
          ...prev,
          status: newStatus,
          lastUpdate: new Date(),
          currentLocation: locationData,
        }));

        if (socket) {
          socket.emit('worker_status_update', {
            workerId,
            status: newStatus,
            location: locationData,
          });
        }

        return updatedWorker;
      } catch (error) {
        return handleError(error, 'Error al actualizar estado del worker');
      }
    },
    [worker, location, socket, handleError]
  );

  // Función para aceptar una entrega
  const acceptDelivery = useCallback(
    async (deliveryId, locationData) => {
      try {
        if (!worker) throw new Error('No autenticado');

        const workerId = worker._id;

        const updatedDelivery = await fetcher(
          `/api/workers/${workerId}/deliveries/${deliveryId}/accept`,
          'POST',
          {
            location: {
              type: 'Point',
              coordinates: [locationData.longitude, locationData.latitude],
            },
          }
        );

        mutate(
          `/api/workers/${workerId}/active-deliveries`,
          (deliveries) => [updatedDelivery, ...deliveries],
          false
        );

        mutate(
          `/api/workers/${workerId}/current-delivery`,
          updatedDelivery,
          false
        );

        if (socket) {
          socket.emit('delivery_accepted', {
            deliveryId,
            workerId,
            location: locationData,
            status: 'accepted',
          });
        }

        return { success: true, data: updatedDelivery };
      } catch (error) {
        return handleError(error, 'Error al aceptar la entrega');
      }
    },
    [worker, socket, handleError]
  );

  // Función para actualizar el estado de una entrega
  const updateDeliveryStatus = useCallback(
    async (deliveryId, newStatus, locationData) => {
      try {
        if (!worker) throw new Error('No autenticado');

        const workerId = worker._id;

        const updatedDelivery = await fetcher(
          `/api/workers/${workerId}/deliveries/${deliveryId}/status`,
          'PUT',
          {
            status: newStatus,
            location: {
              type: 'Point',
              coordinates: [locationData.longitude, locationData.latitude],
            },
          }
        );

        mutate(
          `/api/workers/${workerId}/active-deliveries`,
          (deliveries) =>
            deliveries.map((delivery) =>
              delivery._id === deliveryId ? updatedDelivery : delivery
            ),
          false
        );

        if (newStatus === 'delivered') {
          mutate(`/api/workers/${workerId}/current-delivery`, null, false);
          await mutate(`/api/workers/${workerId}/dashboard-stats`);
        } else {
          mutate(
            `/api/workers/${workerId}/current-delivery`,
            updatedDelivery,
            false
          );
        }

        if (socket) {
          socket.emit('delivery_status_update', {
            deliveryId,
            workerId,
            status: newStatus,
            location: locationData,
          });
        }

        return { success: true, data: updatedDelivery };
      } catch (error) {
        return handleError(error, 'Error al actualizar estado de la entrega');
      }
    },
    [worker, socket, handleError]
  );

  // Función para reportar un problema en una entrega
  const reportDeliveryIssue = useCallback(
    async (deliveryId, issue) => {
      try {
        if (!worker) throw new Error('No autenticado');

        const updatedDelivery = await fetcher(
          `/api/deliveries/${deliveryId}/issues`,
          'POST',
          issue
        );

        if (issue.requiresCancellation) {
          mutate(
            `/api/workers/${worker._id}/active-deliveries`,
            (deliveries) =>
              deliveries.filter((delivery) => delivery._id !== deliveryId),
            false
          );
          mutate(`/api/workers/${worker._id}/current-delivery`, null, false);
        }

        return { success: true, data: updatedDelivery };
      } catch (error) {
        return handleError(error, 'Error al reportar problema');
      }
    },
    [worker, handleError]
  );

  // Función para optimizar rutas
  const optimizeRoute = useCallback(
    async (orders, currentLocation) => {
      try {
        const data = await fetcher('/api/routes/optimize', 'POST', {
          orders,
          currentLocation,
        });

        if (data.success) {
          mutate('/api/routes', { ...data }, false);
          return { success: true, data: data.data };
        }
        return { success: false, error: data.message };
      } catch (error) {
        return handleError(error, 'Error al optimizar ruta');
      }
    },
    [handleError]
  );

  // Función para manejar el inicio de sesión
  const handleLogin = useCallback(async (credentials, userType) => {
    setAuth((prev) => ({
      ...prev,
      [userType]: { ...prev[userType], loading: true, error: null },
    }));

    try {
      const endpoint = `/api/auth/${userType}/login`;
      const data = await fetcher(endpoint, 'POST', credentials);

      if (!data.success) {
        throw new Error(data.message || 'Error en el inicio de sesión');
      }

      const userToStore = {
        ...data.user,
        token: data.token,
        type: userType,
      };

      localStorage.setItem(
        `currentUser_${userType}`,
        JSON.stringify(userToStore)
      );

      setAuth((prev) => ({
        ...prev,
        [userType]: { user: userToStore, loading: false, error: null },
      }));

      if (userType === 'worker') {
        setWorker(userToStore);
        connectSocket(userToStore.token);
      }

      return { success: true, data };
    } catch (error) {
      const errorMessage =
        error.info?.message || error.message || 'Error de conexión';

      setAuth((prev) => ({
        ...prev,
        [userType]: { ...prev[userType], loading: false, error: errorMessage },
      }));

      return { success: false, message: errorMessage, error };
    }
  }, [connectSocket]);

  // Función para manejar el cierre de sesión
  const handleLogout = useCallback(async (userType) => {
    try {
      localStorage.removeItem(`currentUser_${userType}`);

      setAuth((prev) => ({
        ...prev,
        [userType]: { user: null, loading: false, error: null },
      }));

      if (userType === 'worker') {
        setWorker(null);
        disconnectSocket();
      }

      return { success: true };
    } catch (error) {
      return handleError(error, 'Error en logout');
    }
  }, [disconnectSocket, handleError]);

  // Función para verificar la autenticación
  const checkAuth = useCallback(async (userType) => {
    try {
      const storedUser = localStorage.getItem(`currentUser_${userType}`);
      if (!storedUser) return null;

      const userData = JSON.parse(storedUser);
      const endpoint = `/api/auth/${userType}/verify`;

      const data = await fetcher(endpoint, 'GET', null, {
        headers: { Authorization: `Bearer ${userData.token}` },
      });

      if (!data.success) {
        localStorage.removeItem(`currentUser_${userType}`);
        setAuth((prev) => ({
          ...prev,
          [userType]: { user: null, loading: false, error: null },
        }));
        return null;
      }

      setAuth((prev) => ({
        ...prev,
        [userType]: { user: userData, loading: false, error: null },
      }));

      if (userType === 'worker') {
        setWorker(userData);
        connectSocket(userData.token);
      }

      return userData;
    } catch (error) {
      console.error(`Error verificando autenticación para ${userType}:`, error);
      localStorage.removeItem(`currentUser_${userType}`);
      setAuth((prev) => ({
        ...prev,
        [userType]: { user: null, loading: false, error: error.message },
      }));
      return null;
    }
  }, [connectSocket]);

  // Función para actualizar la disponibilidad del trabajador
  const updateWorkerAvailability = useCallback(
    async (newStatus) => {
      try {
        if (!location) {
          throw new Error(
            'Se requiere acceso a la ubicación para cambiar el estado'
          );
        }

        const response = await updateWorkerStatus(newStatus);

        setWorkerStatus((prev) => ({
          ...prev,
          isAvailable: newStatus === 'active',
          currentStatus: newStatus,
          lastUpdate: new Date(),
        }));

        if (socket) {
          socket.emit('worker_status_update', {
            workerId: worker._id,
            status: newStatus,
            location: {
              type: 'Point',
              coordinates: [location.longitude, location.latitude],
            },
          });
        }

        return { success: true, data: response.data };
      } catch (error) {
        return handleError(
          error,
          'Error al actualizar disponibilidad del worker'
        );
      }
    },
    [location, updateWorkerStatus, socket, worker, handleError]
  );

  // Función para manejar nuevas órdenes de entrega
  const handleNewDeliveryOrder = useCallback((order) => {
    // Lógica para manejar nuevas órdenes
  }, []);

  // Función para actualizar el perfil del trabajador
  const updateWorkerProfile = useCallback(
    async (profileData) => {
      try {
        const data = await fetcher(
          `/api/workers/${worker?._id}`,
          'PUT',
          profileData
        );
        if (data.success) {
          setWorkerProfile(data.data);
          setWorker((prev) => ({ ...prev, ...data.data }));
          return { success: true, data: data.data };
        }
        return { success: false, error: data.message };
      } catch (error) {
        return handleError(error, 'Error al actualizar el perfil');
      }
    },
    [worker, handleError]
  );

  // ===========================
  // Efectos Iniciales
  // ===========================

  // Efecto para inicializar la autenticación al montar el componente
  useEffect(() => {
    const initializeAuth = async () => {
      await Promise.all([
        checkAuth('admin'),
        checkAuth('seller'),
        checkAuth('worker'),
      ]);
    };

    initializeAuth();
  }, [checkAuth]);

  // Efecto para actualizar la ubicación del trabajador en tiempo real
  useEffect(() => {
    if (
      socket &&
      isConnected &&
      worker?._id &&
      location &&
      worker.status === 'active'
    ) {
      const locationData = {
        type: 'Point',
        coordinates: [location.longitude, location.latitude],
      };

      socket.emit('worker_location_update', {
        workerId: worker._id,
        location: locationData,
      });
    }
  }, [socket, isConnected, worker, location]);

  // ===========================
  // Valor del Contexto
  // ===========================

  const value = useMemo(() => {
    // Uso de hooks SWR
    const { stats, isLoading: statsLoading, isError: statsError } = useStats();
    const { alerts, isLoading: alertsLoading, isError: alertsError } = useAlerts();
    const { stores, isLoading: storesLoading, isError: storesError } = useStores();
    const { cooperatives, isLoading: cooperativesLoading, isError: cooperativesError } = useCooperatives();
    const { products, services: storeServices, isLoading: productsServicesLoading, isError: productsServicesError } = useProductsAndServices(currentStoreId);
    const { users, totalUsers, totalPages, currentPage, hasMore, isLoading: usersLoading, isError: usersError } = useUsers();
    const { orders, isLoading: ordersLoading, isError: ordersError } = useOrders();
    const { services, isLoading: servicesLoading, isError: servicesError } = useServices();

    const { activeDeliveries, isLoading: activeDeliveriesLoading, isError: activeDeliveriesError } = useActiveDeliveries(worker?._id);
    const { currentDelivery, isLoading: currentDeliveryLoading, isError: currentDeliveryError } = useCurrentDelivery(worker?._id);
    const { dashboardStats, isLoading: dashboardStatsLoading, isError: dashboardStatsError } = useDashboardStats(worker?._id);

    const { workerEarnings, isLoading: workerEarningsLoading, isError: workerEarningsError } = useWorkerEarnings();
    const { deliveryHistory, isLoading: deliveryHistoryLoading, isError: deliveryHistoryError } = useDeliveryHistory();
    const { workerDocuments, isLoading: workerDocumentsLoading, isError: workerDocumentsError } = useWorkerDocuments();
    const { activeChats, isLoading: activeChatsLoading, isError: activeChatsError } = useActiveChats();
    const { deliveryMetrics, isLoading: deliveryMetricsLoading, isError: deliveryMetricsError } = useDeliveryMetrics();
    const { workerDashboard, isLoading: workerDashboardLoading, isError: workerDashboardError } = useWorkerDashboard(worker?._id);
    const { smartRoutes, isLoading: smartRoutesLoading, isError: smartRoutesError } = useSmartRoutes();
    const { storeDeliveries, isLoading: storeDeliveriesLoading, isError: storeDeliveriesError } = useStoreDeliveries(currentStoreId);
    const { storeDetails, isLoading: storeDetailsLoading, isError: storeDetailsError } = useStoreDetails(currentStoreId);
    const { wholesaleProposals, isLoading: wholesaleProposalsLoading, isError: wholesaleProposalsError } = useWholesaleProposals(worker?._id);

    return {
      // Datos obtenidos por SWR
      stats,
      statsLoading,
      statsError,
      alerts,
      alertsLoading,
      alertsError,
      stores,
      storesLoading,
      storesError,
      cooperatives,
      cooperativesLoading,
      cooperativesError,
      products,
      services: storeServices,
      productsServicesLoading,
      productsServicesError,
      users,
      totalUsers,
      totalPages,
      currentPage,
      hasMore,
      usersLoading,
      usersError,
      orders,
      ordersLoading,
      ordersError,
      services,
      servicesLoading,
      servicesError,

      activeDeliveries,
      activeDeliveriesLoading,
      activeDeliveriesError,
      currentDelivery,
      currentDeliveryLoading,
      currentDeliveryError,
      dashboardStats,
      dashboardStatsLoading,
      dashboardStatsError,

      workerEarnings,
      workerEarningsLoading,
      workerEarningsError,
      deliveryHistory,
      deliveryHistoryLoading,
      deliveryHistoryError,
      workerDocuments,
      workerDocumentsLoading,
      workerDocumentsError,
      activeChats,
      activeChatsLoading,
      activeChatsError,
      deliveryMetrics,
      deliveryMetricsLoading,
      deliveryMetricsError,
      workerDashboard,
      workerDashboardLoading,
      workerDashboardError,
      smartRoutes,
      smartRoutesLoading,
      smartRoutesError,
      storeDeliveries,
      storeDeliveriesLoading,
      storeDeliveriesError,
      storeDetails,
      storeDetailsLoading,
      storeDetailsError,
      wholesaleProposals,
      wholesaleProposalsLoading,
      wholesaleProposalsError,

      // Estados globales
      worker,
      workerLoading,
      workerError,
      error,
      validationErrors,
      notifications,
      socketError,
      currentStoreId,
      setCurrentStoreId,
      currentStore,
      setCurrentStore,
      storeSettings,
      setStoreSettings,
      workerStatus,
      workerProfile,
      auth,

      // Funciones de mutación y acciones
      addStore,
      updateStore,
      deleteStore,
      addCooperative,
      updateCooperative,
      deleteCooperative,
      addProduct,
      updateProduct,
      deleteProduct,
      addService,
      updateService,
      deleteService,
      addUser,
      updateUser,
      deleteUser,
      updateOrderStatus,
      updateWorkerStatus,
      acceptDelivery,
      updateDeliveryStatus,
      reportDeliveryIssue,
      optimizeRoute,
      handleLogin,
      handleLogout,
      checkAuth,
      updateWorkerAvailability,
      handleNewDeliveryOrder,
      updateWorkerProfile,
    };
  }, [
    // Dependencias de los hooks SWR
    useStats,
    useAlerts,
    useStores,
    useCooperatives,
    useProductsAndServices,
    useUsers,
    useOrders,
    useServices,
    useActiveDeliveries,
    useCurrentDelivery,
    useDashboardStats,
    useWorkerEarnings,
    useDeliveryHistory,
    useWorkerDocuments,
    useActiveChats,
    useDeliveryMetrics,
    useWorkerDashboard,
    useSmartRoutes,
    useStoreDeliveries,
    useStoreDetails,
    useWholesaleProposals,

    // Dependencias de los estados y funciones
    worker,
    workerLoading,
    workerError,
    error,
    validationErrors,
    notifications,
    socketError,
    currentStoreId,
    setCurrentStoreId,
    currentStore,
    setCurrentStore,
    storeSettings,
    setStoreSettings,
    workerStatus,
    workerProfile,
    auth,

    // Funciones
    addStore,
    updateStore,
    deleteStore,
    addCooperative,
    updateCooperative,
    deleteCooperative,
    addProduct,
    updateProduct,
    deleteProduct,
    addService,
    updateService,
    deleteService,
    addUser,
    updateUser,
    deleteUser,
    updateOrderStatus,
    updateWorkerStatus,
    acceptDelivery,
    updateDeliveryStatus,
    reportDeliveryIssue,
    optimizeRoute,
    handleLogin,
    handleLogout,
    checkAuth,
    updateWorkerAvailability,
    handleNewDeliveryOrder,
    updateWorkerProfile,
  ]);

  return (
    <GlobalContext.Provider value={value}>{children}</GlobalContext.Provider>
  );
};

// Función auxiliar para obtener la clase CSS según el estado de la orden
const getOrderStatusClass = (status) => {
  switch (status.toLowerCase()) {
    case 'pending':
      return 'status-pending';
    case 'completed':
      return 'status-completed';
    case 'cancelled':
      return 'status-cancelled';
    default:
      return 'status-unknown';
  }
};

// Función auxiliar para formatear cantidades monetarias
const formatCurrency = (amount, currency = 'USD') => {
  return new Intl.NumberFormat('es-ES', {
    style: 'currency',
    currency,
  }).format(amount);
};

export default GlobalContext;