import { useEffect, useState } from "react";
import { useSocket } from "@/lib/socket-context";
import { toast } from "sonner";

/**
 * Notification component that listens for real-time notifications
 * and displays them using toast notifications.
 */
export function NotificationsListener() {
  const { onNotification, isConnected } = useSocket();
  const [initialized, setInitialized] = useState(false);

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

    // Set up notification listener
    const unsubscribe = onNotification((data) => {
      // Display notification based on type
      switch (data.type) {
        case "project_invitation":
          toast.info(data.message, {
            description: `You've been invited to collaborate on ${data.projectName}`,
            action: {
              label: "View Project",
              onClick: () => window.location.href = `/projects/${data.projectId}`,
            },
          });
          break;
        case "group_update":
          toast.info(data.message, {
            description: data.description,
            action: data.projectId && {
              label: "View Groups",
              onClick: () => window.location.href = `/projects/${data.projectId}/groups`,
            },
          });
          break;
        case "person_added":
          toast.success(data.message, {
            description: data.description,
          });
          break;
        case "person_removed":
          toast.info(data.message, {
            description: data.description,
          });
          break;
        default:
          toast.info(data.message);
      }
    });

    setInitialized(true);

    // Clean up on unmount
    return () => {
      unsubscribe();
    };
  }, [isConnected, onNotification]);

  // This component doesn't render anything visible
  return null;
}