"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { io, Socket } from "socket.io-client";
import { useCurrent } from "@/features/auth/api/use-curent";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";

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

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

export const useSocket = () => {
  return useContext(SocketContext);
};

export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
  const [socket, setSocket] = useState<Socket | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const { data: user } = useCurrent();
  const workspaceId = useWorkspaceId();
  const queryClient = useQueryClient();

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

    const socketInstance = io(process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000", {
      path: "/api/socket",
    });

    socketInstance.on("connect", () => {
      console.log("Connected to socket server");
      setIsConnected(true);
      
      // Authenticate with the server
      socketInstance.emit("authenticate");
    });

    socketInstance.on("disconnect", () => {
      console.log("Disconnected from socket server");
      setIsConnected(false);
    });

    // Listen for new notifications
    socketInstance.on("notification", (notification: any) => {
      console.log("Received notification:", notification);
      
      // Invalidate notifications query to refresh the list
      queryClient.invalidateQueries({ queryKey: ["notifications"] });
      
      // Show toast notification
      toast.info(notification.title, {
        description: notification.message,
        duration: 5000,
      });
    });

    setSocket(socketInstance);

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

  // Join/leave workspace rooms when workspace changes
  useEffect(() => {
    if (!socket || !workspaceId) return;

    socket.emit("join-workspace", workspaceId);

    return () => {
      socket.emit("leave-workspace", workspaceId);
    };
  }, [socket, workspaceId]);

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