import classNames from "classnames";
import Loading from "components/Loading";
import Modal from "components/Modal";
import { useModules } from "hooks/useModules";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useSelector } from "react-redux";
import {
  selectTalentProfileModules,
  selectUserData,
} from "redux/User/selector";
import { IframeMessage } from "utils/iframeMessage";
import { SHOPIFY_MODULE_TYPE } from "../../../constants/shopify";
import { selectShopifyStores } from "../../../redux/Shopify/selector";
import reduce from "lodash/reduce";
import config from "config";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { useCurrentProfilePreviewUrl } from "../../../hooks/useCurrentProfilePreviewUrl";
import { ModuleType } from "@komi-app/shared-types"

const CONSUMER_URL = config.client.url;
const TALENT_PREVIEW_URL = CONSUMER_URL + "/talent-profile-preview";

interface IProps {
  show: boolean;
  onCancel(): void;
  deviceType: string;
}

const ProfilePreviewModal: React.FC<IProps> = ({
  show,
  onCancel,
  deviceType,
}) => {
  const [webLoaded, setWebLoaded] = useState(false);
  const [webRect, setWebRect] = useState<DOMRect>();
  const iframeRef = useRef<HTMLIFrameElement | null>(null);

  const isProfilePreviewUrlDomainFixEnabled = useFeatureIsOn(
    FLAGS.FIX_SB_869_PREVIEW_NOT_PLAYING_VIDEOS,
  );
  const profilePreviewUrl = useCurrentProfilePreviewUrl();

  const user = useSelector(selectUserData);
  const talentProfileModules = useSelector(selectTalentProfileModules);
  const stores = useSelector(selectShopifyStores);
  const { thirdPartyData } = useModules();

  const currentModules = useMemo(() => {
    return reduce(
      talentProfileModules,
      (result: any, item: any) => {
        if (
          [
            ModuleType.SHOP_MY_SHELF,
            ModuleType.SHOP_LIST,
            ModuleType.YOUTUBE_COLLECTION,
            ModuleType.BANDSINTOWN,
            ModuleType.SEATED,
            ModuleType.PODCAST_AUTOMATION,
          ].includes(item.type)
        ) {
          const data = thirdPartyData.find((el: any) => el.id === item.id);
          let items;
          switch (item.type) {
            case ModuleType.SHOP_MY_SHELF:
            case ModuleType.SHOP_LIST:
              items = data?.products;
              break;
            case ModuleType.YOUTUBE_COLLECTION:
              items = data?.collection?.items;
              break;
            case ModuleType.BANDSINTOWN:
              items = data?.events || [];
              break;
            case ModuleType.SEATED:
              items = data?.events?.shows || [];
              break;
            case ModuleType.PODCAST_AUTOMATION:
              items = data?.collection?.items || [];
              break;
            default:
              break;
          }
          return [
            ...result,
            {
              ...item,
              items: items || [],
              displayLatest: item.items[0].activeLatestPodcast,
            },
          ];
        }
        if (item.type === ModuleType.GROUP) {
          const items = reduce(
            item.items,
            (newItems: any, element: any) => {
              if (
                [
                  ModuleType.SHOP_MY_SHELF,
                  ModuleType.SHOP_LIST,
                  ModuleType.YOUTUBE_COLLECTION,
                  ModuleType.BANDSINTOWN,
                  ModuleType.PODCAST_AUTOMATION,
                  ModuleType.SEATED,
                ].includes(element.type as ModuleType)
              ) {
                const data = thirdPartyData.find(
                  (el: any) => el.id === element.id,
                );

                let items;
                switch (element.type) {
                  case ModuleType.SHOP_MY_SHELF:
                  case ModuleType.SHOP_LIST:
                    items = data?.products;
                    break;
                  case ModuleType.YOUTUBE_COLLECTION:
                    items = data?.collection?.items;
                    break;
                  case ModuleType.BANDSINTOWN:
                    items = data?.events || [];
                    break;
                  case ModuleType.SEATED:
                    items = data?.events?.shows || [];
                    break;
                  case ModuleType.PODCAST_AUTOMATION:
                    items = data?.collection?.items || [];
                    break;
                  default:
                    break;
                }

                return [
                  ...newItems,
                  {
                    ...element,
                    displayLatest: element.items[0].activeLatestPodcast,
                    items: items || [],
                  },
                ];
              }
              return [...newItems, element];
            },
            [],
          );

          return [
            ...result,
            {
              ...item,
              items,
            },
          ];
        }
        return [...result, item];
      },
      [],
    );
  }, [thirdPartyData, talentProfileModules]);

  const shopifyMerchants = useMemo(() => {
    return talentProfileModules?.reduce((result: any, item) => {
      if (
        [
          SHOPIFY_MODULE_TYPE.SHOPIFY_COLLECTION,
          SHOPIFY_MODULE_TYPE.SHOPIFY_PRODUCT,
        ].includes(item.type)
      ) {
        const storeDomain = (item.items?.[0] as any)?.shop || "";

        const accessToken =
          stores?.find((store) => store.domain === storeDomain)?.accessToken ||
          user?.talentProfile?.shopifyMerchants?.[storeDomain]?.accessToken;
        result[storeDomain] = accessToken;
        return result;
      }
      return result;
    }, {});
  }, [stores, user, talentProfileModules]);

  const handleSendTalentProfile = useCallback(async () => {
    if (!iframeRef) return;
    const message = {
      type: "komi_talent_profile",
      data: {
        ...user,
        talentProfile: {
          ...user?.talentProfile,
          modules: currentModules,
          shopifyMerchants,
        },
      },
    };
    iframeRef.current?.contentWindow?.postMessage(JSON.stringify(message), "*");
    IframeMessage.postMessage(message);

    // trigger scroll 1px to load lazy image
    window.scrollTo(window.scrollX, window.scrollY + 1);
  }, [user, talentProfileModules, shopifyMerchants]);

  const handleMessage = useCallback(
    async (event: MessageEvent) => {
      const { type, data } = event.data;
      switch (type) {
        case "komi_consumer_loaded":
          setWebLoaded(true);
          handleSendTalentProfile();
          break;
        case "komi_consumer_rect":
          if (!!data.height) {
            setWebRect(data);
          }
          break;
        default:
          break;
      }
    },
    [webLoaded, user, talentProfileModules, handleSendTalentProfile],
  );

  useEffect(() => {
    IframeMessage.bindEvent(window, "message", handleMessage);
    return () => {
      IframeMessage.unbindEvent(window, "message", handleMessage);
    };
  }, [handleMessage]);

  useEffect(() => {
    handleSendTalentProfile();
  }, [shopifyMerchants, talentProfileModules, handleSendTalentProfile]);

  useEffect(() => {
    if (!webRect || !iframeRef) return;
    iframeRef.current?.setAttribute("style", `height:${webRect?.height}px`);
  }, [webRect]);

  return (
    <Modal
      centered
      footer={null}
      className={classNames({
        "profile-preview-modal": true,
        [deviceType]: true,
      })}
      visible={show}
      onCancel={onCancel}
    >
      {!webLoaded && <Loading />}
      <iframe
        ref={iframeRef}
        id="consumer-web"
        src={
          isProfilePreviewUrlDomainFixEnabled
            ? profilePreviewUrl
            : `${TALENT_PREVIEW_URL}`
        }
        frameBorder="0"
      />
    </Modal>
  );
};

export default ProfilePreviewModal;
