import { useApolloClient } from "@apollo/client/react";
import { getToken } from "@firebase/messaging";
import axios from "axios";
import { useEffect } from "react";
import { messaging, requestForToken } from "../../firebase/firebase.utils";
import ChatPopupComponent from "../chat-popup/chat-popup.component";
import "./chat-affix.styles.scss";
import { registerMessagingHandlers, unregisterMessagingHandlers } from "./registerMessagingSocketHandlers";
import { useSocket } from "../../contexts/SocketIO/useSocket.js";

export function ChatAffixContainer({ bodyshop, chatVisible, currentUser }) {
  const client = useApolloClient();
  const { socket } = useSocket();

  // 1) FCM subscription (independent of socket handler registration)
  useEffect(() => {
    if (!bodyshop?.messagingservicesid) return;

    async function subscribeToTopicForFCMNotification() {
      try {
        await requestForToken();
        await axios.post("/notifications/subscribe", {
          fcm_tokens: await getToken(messaging, {
            vapidKey: import.meta.env.VITE_APP_FIREBASE_PUBLIC_VAPID_KEY
          }),
          type: "messaging",
          imexshopid: bodyshop.imexshopid
        });
      } catch (error) {
        console.log("Error attempting to subscribe to messaging topic: ", error);
      }
    }

    subscribeToTopicForFCMNotification();
  }, [bodyshop?.messagingservicesid, bodyshop?.imexshopid]);

  // 2) Register socket handlers as soon as socket is connected (regardless of chatVisible)
  useEffect(() => {
    if (!socket) return;
    if (!bodyshop?.messagingservicesid) return;
    if (!bodyshop?.id) return;

    // If socket isn't connected yet, ensure no stale handlers remain.
    if (!socket.connected) {
      unregisterMessagingHandlers({ socket });
      return;
    }

    // Prevent duplicate listeners if this effect runs more than once.
    unregisterMessagingHandlers({ socket });

    registerMessagingHandlers({
      socket,
      client,
      currentUser,
      bodyshop
    });

    return () => {
      unregisterMessagingHandlers({ socket });
    };
  }, [socket, socket?.connected, bodyshop?.id, bodyshop?.messagingservicesid, client, currentUser?.email]);

  if (!bodyshop?.messagingservicesid) return <></>;

  return (
    <div className={`chat-affix ${chatVisible ? "chat-affix-open" : ""}`}>
      {bodyshop?.messagingservicesid ? <ChatPopupComponent /> : null}
    </div>
  );
}

export default ChatAffixContainer;
