import { useApolloClient } from "@apollo/client";
import { getToken } from "@firebase/messaging";
import axios from "axios";
import React, { useContext, useEffect } from "react";
import { useTranslation } from "react-i18next";
import SocketContext from "../../contexts/SocketIO/socketContext";
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";

export function ChatAffixContainer({ bodyshop, chatVisible }) {
  const { t } = useTranslation();
  const client = useApolloClient();
  const { socket } = useContext(SocketContext);

  useEffect(() => {
    if (!bodyshop || !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();

    //Register WS handlers
    if (socket && socket.connected) {
      registerMessagingHandlers({ socket, client });
    }

    return () => {
      if (socket && socket.connected) {
        unregisterMessagingHandlers({ socket });
      }
    };
  }, [bodyshop, socket, t, client]);

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

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

export default ChatAffixContainer;
