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();

  const messagingServicesId = bodyshop?.messagingservicesid;
  const bodyshopId = bodyshop?.id;
  const imexshopid = bodyshop?.imexshopid;

  const messagingEnabled = Boolean(messagingServicesId);

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

    (async () => {
      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
        });
      } catch (error) {
        console.log("Error attempting to subscribe to messaging topic: ", error);
      }
    })();
  }, [messagingEnabled, imexshopid]);

  useEffect(() => {
    if (!socket) return;
    if (!messagingEnabled) return;
    if (!bodyshopId) return;

    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, messagingEnabled, bodyshopId, client, currentUser?.email, bodyshop]);

  if (!messagingEnabled) return null;

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

export default ChatAffixContainer;
