"use client";
import { getSocket } from "@/lib/hooks/use-socket";
import React from "react";
import { Socket } from "socket.io-client";

type SocketContextValues = {
  socket?: Socket;
};

export const SocketContext = React.createContext<
  SocketContextValues | undefined
>(undefined);

export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
  const [socket, setSocket] = React.useState<Socket | undefined>();

  React.useEffect(() => {
    // Initialize the socket when the provider mounts
    const newSocket = getSocket();
    setSocket(newSocket);
    console.log("Socket connected");

    // Cleanup function to disconnect the socket when the provider unmounts
    return () => {
      newSocket.disconnect();
      console.log("Socket disconnected");
    };
  }, []);

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

export const useSocket = () => {
  const context = React.useContext(SocketContext);

  return { socket: context?.socket };
};
