import { useMutation, useQuery } from "@apollo/client/react";
import { logImEXEvent, messaging } from "../../firebase/firebase.utils";
import { QUERY_ALL_ASSOCIATIONS, UPDATE_ACTIVE_ASSOCIATION } from "../../graphql/associations.queries";
import AlertComponent from "../alert/alert.component";
import ProfileShopsComponent from "./profile-shops.component";
import axios from "axios";
import { getToken } from "@firebase/messaging";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser
});

const mapDispatchToProps = () => ({});

export default connect(mapStateToProps, mapDispatchToProps)(ProfileShopsContainer);

export function ProfileShopsContainer({ bodyshop, currentUser }) {
  const { loading, error, data } = useQuery(QUERY_ALL_ASSOCIATIONS, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    variables: {
      email: currentUser.email
    },
    skip: !currentUser
  });
  const [updateActiveAssociation] = useMutation(UPDATE_ACTIVE_ASSOCIATION);

  const updateActiveShop = async (newActiveAssocId) => {
    logImEXEvent("profile_change_active_shop");

    try {
      const fcm_tokens = await getToken(messaging);

      await axios.post("/notifications/unsubscribe", {
        fcm_tokens,
        imexshopid: bodyshop.imexshopid,
        type: "messaging"
      });
    } catch {
      console.log("No FCM token. Skipping unsubscribe.");
    }

    await updateActiveAssociation({
      variables: {
        newActiveAssocId: newActiveAssocId
      }
    });

    //Force window refresh.

    //Ping the new partner to refresh.
    axios.post("http://localhost:1337/refresh");

    window.location.reload();
  };

  if (error) return <AlertComponent type="error" title={error.message} />;
  return (
    <ProfileShopsComponent
      loading={loading}
      data={data ? data.associations : null}
      updateActiveShop={updateActiveShop}
    />
  );
}
