"use client";

import { useEffect } from "react";
import { useAppDispatch } from "../hooks/hooks";
import { socketInstance } from "../utils/socket";
import { appendMessage, setMessageList } from "../store/Slice/messageSlice";
import { setChatList } from "../store/Slice/chatUserSlice";
import Cookies from "js-cookie";

export default function ListenAllEvents() {
  const dispatch = useAppDispatch();
  const socket = socketInstance();

  // Function to play sound
  const newMessageCommingSound = () => {
    const audio = new Audio("/audio/achive-sound-132273.mp3");
    audio.play().catch((error) => {
      console.error("Error playing sound:", error);
    });
  };

  useEffect(() => {
    const myUserId = Cookies.get("USERID")?.toString();

    const handleMessage = (messageData) => {
      console.log("📩 New message from socket:", messageData);

      // Only play sound if the message is from someone else
      if (messageData?.from_user?.toString() !== myUserId) {
        newMessageCommingSound();
      }

      // Add the message to Redux state
      dispatch(appendMessage(messageData));
    };

    const handleMessageList = (messageListData) => {
      console.log("📨 New message list:", messageListData);
      dispatch(setMessageList(messageListData));
    };

    const handleUserList = (userListData) => {
      console.log("👥 New user chat list:", userListData);
      dispatch(setChatList(userListData));
    };

    socket.on("message", handleMessage);
    socket.on("MessageList", handleMessageList);
    socket.on("UserChatList", handleUserList);

    return () => {
      socket.off("message", handleMessage);
      socket.off("MessageList", handleMessageList);
      socket.off("UserChatList", handleUserList);
    };
  }, []);
}
