import { useApolloClient } from "@apollo/client";
import { getToken, onMessage } from "@firebase/messaging";
import { Button, notification, Space } from "antd";
import axios from "axios";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { messaging, requestForToken } from "../../firebase/firebase.utils";
import FcmHandler from "../../utils/fcm-handler";
import ChatPopupComponent from "../chat-popup/chat-popup.component";
import "./chat-affix.styles.scss";

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

  useEffect(() => {
    if (!bodyshop || !bodyshop.messagingservicesid) return;

    async function SubscribeToTopic() {
      try {
        const r = 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
        });
        console.log("FCM Topic Subscription", r.data);
      } catch (error) {
        console.log("Error attempting to subscribe to messaging topic: ", error);
        notification.open({
          key: "fcm",
          type: "warning",
          message: t("general.errors.fcm"),
          btn: (
            <Space>
              <Button
                onClick={async () => {
                  await requestForToken();
                  SubscribeToTopic();
                }}
              >
                {t("general.actions.tryagain")}
              </Button>
              <Button
                onClick={() => {
                  const win = window.open(
                    "https://help.imex.online/en/article/enabling-notifications-o978xi/",
                    "_blank"
                  );
                  win.focus();
                }}
              >
                {t("general.labels.help")}
              </Button>
            </Space>
          )
        });
      }
    }

    SubscribeToTopic();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bodyshop]);

  useEffect(() => {
    function handleMessage(payload) {
      FcmHandler({
        client,
        payload: (payload && payload.data && payload.data.data) || payload.data
      });
    }

    let stopMessageListener, channel;
    try {
      stopMessageListener = onMessage(messaging, handleMessage);
      channel = new BroadcastChannel("imex-sw-messages");
      channel.addEventListener("message", handleMessage);
    } catch (error) {
      console.log("Unable to set event listeners.");
    }
    return () => {
      stopMessageListener && stopMessageListener();
      channel && channel.removeEventListener("message", handleMessage);
    };
  }, [client]);

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

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

export default ChatAffixContainer;
