import React, { useEffect, useContext } from "react";
import { toast } from "react-toastify";
import { SSEContext } from "./SSEContext";
import { AuthContext } from "./AuthContext";

/**
 * NotificationProvider integrates SSE events with toast notifications
 * Automatically displays toast notifications for various real-time events
 */
const NotificationProvider = ({ children }) => {
  const { connected, on, off } = useContext(SSEContext);
  const { auth } = useContext(AuthContext);

  // Watch connection state for connection status toasts
  useEffect(() => {
    if (connected) {
      toast.success("Connected to real-time updates", {
        toastId: "sse-connected", // Prevent duplicate toasts
      });
    } else {
      toast.warning("Connection lost. Reconnecting...", {
        toastId: "sse-reconnecting",
      });
    }
  }, [connected]);

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

    // Event-related notifications
    const handleEventUpdate = (data) => {
      if (data.type === "new_event") {
        toast.info(`New event: ${data.event?.title || "Check it out!"}`, {
          toastId: `event-new-${data.event?._id}`,
        });
      } else if (data.type === "participants_updated") {
        // Optional: Show notification when someone joins an event
        // Commenting out to avoid notification spam
        // toast.info("Event participants updated", {
        //   toastId: `event-participants-${data.eventId}`,
        // });
      } else if (data.type === "event_updated") {
        toast.info("Event details have been updated", {
          toastId: `event-updated-${data.event?._id}`,
        });
      } else if (data.type === "event_deleted") {
        toast.warning("An event has been cancelled", {
          toastId: `event-deleted-${data.eventId}`,
        });
      }
    };

    // Task-related notifications
    const handleTaskUpdate = (data) => {
      if (data.type === "new_task") {
        toast.info(`New task available: ${data.task?.description || "Check tasks"}`, {
          toastId: `task-new-${data.task?._id}`,
        });
      } else if (data.type === "task_completed") {
        // Check if this task was completed by another user
        if (data.completedBy && auth.user && data.completedBy !== auth.user.id) {
          toast.success(`Task completed by another user!`, {
            toastId: `task-completed-${data.taskId}`,
          });
        }
      } else if (data.type === "task_updated") {
        toast.info("A task has been updated", {
          toastId: `task-updated-${data.task?._id}`,
        });
      } else if (data.type === "task_deleted") {
        toast.warning("A task has been removed", {
          toastId: `task-deleted-${data.taskId}`,
        });
      }
    };

    // Street adoption notifications
    const handleStreetUpdate = (data) => {
      if (data.type === "street_adopted") {
        const streetName = data.street?.name || "A street";
        const userName = data.adoptedBy?.name || "Someone";
        
        // Only notify if it wasn't adopted by the current user
        if (data.adoptedBy?._id !== auth.user?.id) {
          toast.info(`${streetName} was adopted by ${userName}`, {
            toastId: `street-adopted-${data.street?._id}`,
          });
        }
      } else if (data.type === "street_unadopted") {
        const streetName = data.street?.name || "A street";
        toast.info(`${streetName} is now available for adoption`, {
          toastId: `street-unadopted-${data.street?._id}`,
        });
      }
    };

    // Achievement/Badge notifications
    const handleAchievementUnlocked = (data) => {
      const badgeName = data.badge?.name || data.achievement?.name || "Achievement";
      const badgeDescription = data.badge?.description || data.achievement?.description || "You've unlocked a new achievement!";
      
      toast.success(
        <div>
          <strong>Achievement Unlocked!</strong>
          <div>{badgeName}</div>
          <small>{badgeDescription}</small>
        </div>,
        {
          toastId: `achievement-${data.badge?._id || data.achievement?.id}`,
          autoClose: 7000, // Show longer for achievements
        }
      );
    };

    // Post/Comment notifications
    const handleNewPost = (data) => {
      const authorName = data.post?.author?.name || "Someone";
      toast.info(`${authorName} created a new post`, {
        toastId: `post-new-${data.post?._id}`,
      });
    };

    const handleNewComment = (data) => {
      const authorName = data.comment?.author?.name || "Someone";
      // Only notify if comment wasn't by current user
      if (data.comment?.author?._id !== auth.user?.id) {
        toast.info(`${authorName} commented on a post`, {
          toastId: `comment-new-${data.comment?._id}`,
        });
      }
    };

    // Generic notification handler (fallback)
    const handleNotification = (data) => {
      const type = data.type || "info";
      const message = data.message || "New notification";
      
      switch (type) {
        case "success":
          toast.success(message, { toastId: `notification-${Date.now()}` });
          break;
        case "error":
          toast.error(message, { toastId: `notification-${Date.now()}` });
          break;
        case "warning":
          toast.warning(message, { toastId: `notification-${Date.now()}` });
          break;
        default:
          toast.info(message, { toastId: `notification-${Date.now()}` });
      }
    };

    // Subscribe to SSE events
    on("eventUpdate", handleEventUpdate);
    on("taskUpdate", handleTaskUpdate);
    on("streetUpdate", handleStreetUpdate);
    on("achievementUnlocked", handleAchievementUnlocked);
    on("badgeUnlocked", handleAchievementUnlocked); // Same handler
    on("newPost", handleNewPost);
    on("newComment", handleNewComment);
    on("notification", handleNotification); // Generic fallback

    // Cleanup on unmount
    return () => {
      off("eventUpdate", handleEventUpdate);
      off("taskUpdate", handleTaskUpdate);
      off("streetUpdate", handleStreetUpdate);
      off("achievementUnlocked", handleAchievementUnlocked);
      off("badgeUnlocked", handleAchievementUnlocked);
      off("newPost", handleNewPost);
      off("newComment", handleNewComment);
      off("notification", handleNotification);
    };
  }, [connected, on, off, auth.user]);

  return <>{children}</>;
};

export default NotificationProvider;

/**
 * Utility functions for triggering toasts from components
 */
export const notify = {
  success: (message, options = {}) => {
    toast.success(message, options);
  },
  error: (message, options = {}) => {
    toast.error(message, options);
  },
  info: (message, options = {}) => {
    toast.info(message, options);
  },
  warning: (message, options = {}) => {
    toast.warning(message, options);
  },
  /**
   * Dismiss a specific toast by ID
   * @param {string} toastId - The ID of the toast to dismiss
   */
  dismiss: (toastId) => {
    toast.dismiss(toastId);
  },
  /**
   * Dismiss all toasts
   */
  dismissAll: () => {
    toast.dismiss();
  },
};
