import { useWindowSize } from "hooks";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useSelector } from "react-redux";
import { selectActiveModule } from "redux/Talent/selector";
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 DotLoading from "components/DotLoading";
import { default as classnames } from "classnames";
import config from "config";

const CONSUMER_URL = config.client.url;
const TALENT_PREVIEW_URL = CONSUMER_URL + "/podcast-preview";
interface IProps {
  data: any;
  activeLatestPodcast: any;
}
const PodCastAutomationReview: React.FC<IProps> = ({
  data,
  activeLatestPodcast,
}) => {
  console.log(data);
  const iframeRef = useRef<HTMLIFrameElement | null>(null);
  const { width } = useWindowSize();

  const user = useSelector(selectUserData);

  const talentProfileModules = useSelector(selectTalentProfileModules);

  const stores = useSelector(selectShopifyStores);
  const activeModule = useSelector(selectActiveModule);

  const [webLoaded, setWebLoaded] = useState(false);
  const [webRect, setWebRect] = useState<DOMRect>();
  const [showModal] = useState(false);
  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_podcast_automation_profile",
      data: {
        ...user,
        talentProfile: {
          ...user?.talentProfile,
          modules: {
            ...user?.talentProfile,
            displayLatest: activeLatestPodcast,
            items: data,
          },
        },
      },
    };

    iframeRef.current?.contentWindow?.postMessage(JSON.stringify(message), "*");
    IframeMessage.postMessage(message);

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

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

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

  useEffect(() => {
    handleSendTalentProfile();
  }, [shopifyMerchants, talentProfileModules, handleSendTalentProfile]);
  const maxHeight = useMemo(() => {
    if (data.length === 1) {
      return 286;
    }
    if (activeLatestPodcast) {
      return data.length > 4 ? 515 : 286 + (data.length - 1) * 131;
    }
    return data.length > 3 ? 238 : (data.length - 1) * 135 + 10 + 135;
  }, [data, activeLatestPodcast]);
  useEffect(() => {
    if (!webLoaded) return;
    iframeRef?.current?.setAttribute(
      "style",
      `height:${webRect?.height || 180}px; max-height:${maxHeight}px;`
    );
  }, [webRect, webLoaded, maxHeight]);
  useEffect(() => {
    if (!!activeModule) {
      if (!iframeRef) return;
      const message = {
        type: "komi_talent_profile_active_module",
        data: {
          activeModule,
        },
      };
      iframeRef.current?.contentWindow?.postMessage(
        JSON.stringify(message),
        "*"
      );
      IframeMessage.postMessage(message);
    }
  }, [iframeRef, activeModule]);

  return (
    <div
      className="profile-preview-wrapper"
      style={{
        width: width ? (width >= 1138 ? 337 : (width - 96) / 3) : 337,
      }}
    >
      {(!webLoaded || !webRect?.height) && (
        <div
          style={{
            height: webRect?.height || 180,
          }}
          className={classnames({
            "preview-podcast-loading": true,
          })}
        >
          <DotLoading isDarken={true} />
        </div>
      )}

      <iframe
        ref={iframeRef}
        id="consumer-podcast-web"
        src={`${TALENT_PREVIEW_URL}`}
        frameBorder="0"
      />
    </div>
  );
};

export default PodCastAutomationReview;
