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 { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { messaging, requestForToken } from "../../firebase/firebase.utils";
import { selectChatVisible } from "../../redux/messaging/messaging.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import FcmHandler from "../../utils/fcm-handler";
import ChatPopupComponent from "../chat-popup/chat-popup.component";
import "./chat-affix.styles.scss";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  chatVisible: selectChatVisible,
});

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: process.env.REACT_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({
          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 stopMessageListenr, channel;
    try {
      stopMessageListenr = onMessage(messaging, handleMessage);
      channel = new BroadcastChannel("imex-sw-messages");
      channel.addEventListener("message", handleMessage);
    } catch (error) {
      console.log("Unable to set event listeners.");
    }
    return () => {
      stopMessageListenr && stopMessageListenr();
      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 connect(mapStateToProps, null)(ChatAffixContainer);
