"use client";

import * as React from "react";
import { io, type Socket } from "socket.io-client";
import { useAuth } from "./auth-provider";

interface SocketContextType {
	socket: Socket | null;
	isConnected: boolean;
}

const SocketContext = React.createContext<SocketContextType>({
	socket: null,
	isConnected: false,
});

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

export function SocketProvider({ children }: { children: React.ReactNode }) {
	const { isAuthenticated } = useAuth();
	const [socket, setSocket] = React.useState<Socket | null>(null);
	const [isConnected, setIsConnected] = React.useState(false);

	React.useEffect(() => {
		if (isAuthenticated) {
			const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";
			const socketInstance = io(apiUrl, {
				withCredentials: true,
				transports: ["websocket"],
			});

			socketInstance.on("connect", () => {
				setIsConnected(true);
			});

			socketInstance.on("disconnect", () => {
				setIsConnected(false);
			});

			setSocket(socketInstance);

			return () => {
				socketInstance.disconnect();
			};
		} else {
			setSocket(null);
			setIsConnected(false);
		}
	}, [isAuthenticated]);

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