import { useApolloClient } from "@apollo/client";
import { getToken } from "@firebase/messaging";
import axios from "axios";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
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 }) {
  const { t } = useTranslation();
  const client = useApolloClient();
  const { socket } = useSocket();

  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 WebSocket handlers
    if (socket && socket.connected) {
      registerMessagingHandlers({ socket, client });

      return () => {
        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;
