import { LoadingOutlined } from "@ant-design/icons";
import { Card, Col, Row, Spin } from "antd";
import message from "antd/lib/message";
import { disableBodyScroll, enableBodyScroll } from "body-scroll-lock";
import classNames from "classnames";
import BlockingEdit from "components/BlockingEdit";
import LocalizationSelect from "components/LocalizationSelect";
import { Text } from "components/Typography";
import { profileTabs } from "constants/profile";
import { DARK_THEME } from "constants/profile-theme";
import { SEGMENT_EVENTS } from "constants/segment";
import { useAnalytics } from "hooks/useAnalytics";
import { useAutoSave } from "hooks/useAutoSave";
import useScrollY from "hooks/useScrollY";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useDispatch } from "react-redux";
import { Prompt } from "react-router";
import { useHistory, useLocation } from "react-router-dom";
import { useTypedSelector } from "redux/rootReducer";
import { setActiveModuleAction } from "redux/Talent/actions";
import {
  selectIsAutoSaveSuccess,
  selectIsPublished,
  selectLoadingAutoSave,
  selectLoadingPublish,
  selectModuleLoading,
  selectTalentProfile,
  selectTalentProfileModules,
  selectUserData,
  selectUserLoading,
} from "redux/User/selector";
import {
  TalentProfileDisplayNameTypes,
  TalentProfileThemeColor,
  TalentProfileThemeTypes,
} from "redux/User/types";
import notification from "utils/notification";
import ProfileHeader from "./Header";
import ModuleList from "./ModuleList";
import "./Profile.scss";
import ProfileSocialLinks from "./ProfileModule/ProfileSocialLinks";
import ProfileTheme from "./ProfileModule/ProfileTheme";
import ProfilePreview from "./ProfilePreview/ProfilePreview";
import upcoming, { adjust } from "utils/upcoming";
import {
  FLAGS,
  IfFeature,
  IfFeatureEnabled,
  useFeatureIsOn,
} from "@komi-app/flags-sdk";
import { TemplateSelectionModal } from "../../components/TemplateSelectionModal/TemplateSelectionModal";
import { useWindowSize } from "../../hooks";
import { useHasTemplates } from "hooks/useHasTemplates";
import When from "@komi-app/when";
import ProfilePreviewDrawer from "./ProfilePreviewDrawer/ProfilePreviewDrawer";
import { Button } from "@komi-app/creator-ui";
import { CurrentTalentSiteLinkCopy } from "../../components/CurrentTalentSiteLinkCopy/CurrentTalentSiteLinkCopy";
import { TemplateSelectionModalV2 } from "components/TemplateSelectionModalV2/TemplateSelectionModalV2";
import { ModuleType } from "@komi-app/shared-types"
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";

import Cello from "../Cello";

const Profile: React.FC = () => {
  const {
    title,
    isBlockingEditState,
    isPublished,
    isOnModulesPage,
    loadingPublish,
    handlePublish,
    onCheckBeforeChangeRouter,
    renderLoadingAutoSave,
    renderTab,
    onStartFromScratch,
    onStartWithTemplates,
  } = useProfile();
  const { width } = useWindowSize();

  const isSmallScreen = width && width <= 768;
  const isShowingDrawerPreview = isSmallScreen;

  const isCopyUrlPromptEnabled = useFeatureIsOn(
    FLAGS.FEAT_SB_357_COPY_SITE_LINK
  );

  if (isCopyUrlPromptEnabled) {
    return (
      <React.Fragment>
        {isBlockingEditState ? (
          <BlockingEdit />
        ) : (
          <>
            <IfFeatureEnabled feature={FLAGS.GS_146_ADD_TEMPLATE_SELECTION}>
              <IfFeature
                feature={FLAGS.FEAT_SB_447_MODULE_TEMPLATES}
                enabled={
                  <When
                    value={isOnModulesPage}
                    then={
                      <>
                        <TemplateSelectionModalV2
                          onStartFromScratch={onStartFromScratch}
                          onStartWithTemplates={onStartWithTemplates}
                        />
                      </>
                    }
                  />
                }
                disabled={
                  <IfFeature
                    feature={
                      FLAGS.FEAT_SB_358_SHOW_MODULE_MENU_AFTER_NO_TEMPLATE
                    }
                    enabled={
                      <TemplateSelectionModal
                        onStartFromScratch={onStartFromScratch}
                      />
                    }
                    disabled={<TemplateSelectionModal />}
                  />
                }
              />
            </IfFeatureEnabled>
            <IfFeatureEnabled feature={FLAGS.FEAT_CELLO_REFERRAL}>
              <Cello />
            </IfFeatureEnabled>
            <When
              value={isShowingDrawerPreview}
              then={<ProfilePreviewDrawer />}
            />
            <Prompt message={onCheckBeforeChangeRouter} />

            <div
              className={classNames(
                "profile-wrapper",
                "profile-wrapper__sb357"
              )}
              data-testid="profile__wrapper"
            >
              <Row align="middle" gutter={24}>
                <Col span={isSmallScreen ? undefined : 5}>
                  <Text preset="bold20">{title}</Text>
                </Col>
                <Col flex="auto" style={{ padding: 0 }} />
                <When
                  value={!isSmallScreen}
                  then={
                    <>
                      <Col flex="auto">
                        <CurrentTalentSiteLinkCopy />
                      </Col>
                    </>
                  }
                />
                <Col>
                  <Row align="middle">
                    {renderLoadingAutoSave()}
                    <Button
                      loading={loadingPublish}
                      onClick={handlePublish}
                      disabled={isPublished || loadingPublish}
                      data-testid="profile__publish"
                      label={
                        loadingPublish
                          ? "PUBLISHING"
                          : isPublished
                            ? "PUBLISHED"
                            : "PUBLISH"
                      }
                    />
                  </Row>
                </Col>
              </Row>
              <When
                value={isSmallScreen}
                then={
                  <Row>
                    <Col span={24}>
                      <CurrentTalentSiteLinkCopy />
                    </Col>
                  </Row>
                }
              />
              <Row
                className={classNames("profile-wrapper__content")}
                gutter={32}
              >
                <Col span={isShowingDrawerPreview ? 24 : 16}>{renderTab()}</Col>
                <When
                  value={!isShowingDrawerPreview}
                  then={
                    <Col
                      span={isShowingDrawerPreview ? 0 : 8}
                      className="profile-wrapper__tab-preview"
                    >
                      <div className="profile-review">
                        <ProfilePreview data-testid="profile__preview" />
                      </div>
                    </Col>
                  }
                />
              </Row>
            </div>
          </>
        )}
      </React.Fragment>
    );
  }

  return (
    <React.Fragment>
      {isBlockingEditState ? (
        <BlockingEdit />
      ) : (
        <>
          <IfFeatureEnabled feature={FLAGS.GS_146_ADD_TEMPLATE_SELECTION}>
            <TemplateSelectionModal />
          </IfFeatureEnabled>
          <When
            value={isShowingDrawerPreview}
            then={<ProfilePreviewDrawer />}
          />
          <Prompt message={onCheckBeforeChangeRouter} />

          <div className="profile-wrapper" data-testid="profile__wrapper">
            <Row align="middle" justify="space-between">
              <Col>
                <Text preset="bold20">{title}</Text>
              </Col>
              <Col>
                <Row align="middle">
                  {renderLoadingAutoSave()}
                  <Button
                    loading={loadingPublish}
                    onClick={handlePublish}
                    disabled={isPublished || loadingPublish}
                    data-testid="profile__publish"
                    label={
                      loadingPublish
                        ? "PUBLISHING"
                        : isPublished
                          ? "PUBLISHED"
                          : "PUBLISH"
                    }
                  />
                </Row>
              </Col>
            </Row>
            <Row
              className={classNames("profile-wrapper__content", "m__t--16")}
              gutter={32}
            >
              <Col span={isShowingDrawerPreview ? 24 : 16}>{renderTab()}</Col>
              <When
                value={!isShowingDrawerPreview}
                then={
                  <Col
                    span={isShowingDrawerPreview ? 0 : 8}
                    className="profile-wrapper__tab-preview"
                  >
                    <div className="profile-review">
                      <ProfilePreview data-testid="profile__preview" />
                    </div>
                  </Col>
                }
              />
            </Row>
          </div>
        </>
      )}
    </React.Fragment>
  );
};

export const useProfile = () => {
  useScrollY();
  const { sendSegmentEvent } = useAnalytics();
  const {
    localizationSelected,
    setLocalizationSelected,
    setIsVisiblePublish,
    isBlockingEditState,
    onCheckBeforeChangeRouter,
    handleChangeLocalization,
    setVisibleConfirmPublish,
  } = useAutoSave();
  const router = useHistory();
  const dispatch = useDispatch();
  const location = useLocation();
  const isAutoSaveSuccess = useTypedSelector(selectIsAutoSaveSuccess);
  const [defaultCustomColor, setDefaultCustomColor] =
    useState<TalentProfileThemeColor>();
  const [firstThemeType, setFirstThemeType] =
    useState<TalentProfileThemeTypes>();
  const loading = useTypedSelector(selectUserLoading);
  const loadingAutoSave = useTypedSelector(selectLoadingAutoSave);

  const talentProfile = useTypedSelector(selectTalentProfile);
  const modules = useTypedSelector(selectTalentProfileModules);
  const user = useTypedSelector(selectUserData);
  const isPublished = useTypedSelector(selectIsPublished);
  const loadingPublish = useTypedSelector(selectLoadingPublish);
  const moduleLoading = useTypedSelector(selectModuleLoading);

  const [showAddModuleMenu, setShowAddModuleMenu] = useState(false);

  const hasTemplateModules = useHasTemplates();

  const isContentMenuEnabled = useFeatureIsOn(FLAGS.FEAT_SB_389_ADD_ITEM_MENU);
  const isTemplatesV2Enabled = useFeatureIsOn(
    FLAGS.FEAT_SB_447_MODULE_TEMPLATES
  );
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking()
  const viewGoalTemplatePage = createTracker(CreatorEvent.VIEW_GOAL_TEMPLATE_PAGE)
  const viewHeaderTab = createTracker(CreatorEvent.VIEW_HEADER_TAB)
  const viewThemeTab = createTracker(CreatorEvent.VIEW_THEME_TAB)
  const viewSocialLinksTab = createTracker(CreatorEvent.VIEW_SOCIAL_LINKS_TAB)
  const viewModuleTab = createTracker(CreatorEvent.VIEW_MODULES_TAB)

  const { pathname } = location;
  const getCurrentTab = (pathname: string) => {
    const [head, tail] = pathname.split("/admin");
    return (
      (tail && tail.substring(1)) || (head && head.substring(1)) || "header"
    );
  };
  const [tab, setTab] = useState<string>(getCurrentTab(pathname));

  const isOnModulesPage = tab === "modules";

  const title = useMemo(() => {
    const tabs = profileTabs(isContentMenuEnabled);
    const current = tabs.find(({ key }) => key === tab);
    return current ? current.name : "Profile Editor";
  }, [tab, isContentMenuEnabled]);

  const { isUpcoming } = upcoming();

  const disableBody = (target: any) => {
    disableBodyScroll(target);
  };
  const enableBody = (target: any) => enableBodyScroll(target);
  useEffect(() => {
    setTimeout(() => {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    }, 500);
  }, []);

  useEffect(() => {
    if (!user || firstThemeType) {
      return;
    }
    if (!firstThemeType) {
      setFirstThemeType(user?.talentProfile?.themeType);
      setDefaultCustomColor(user?.talentProfile?.themeColor || DARK_THEME);
    }
  }, [user, firstThemeType]);

  useEffect(() => {
    setTab(getCurrentTab(pathname));
  }, [pathname]);

  const onStartFromScratch = useCallback(() => {
    if (isContentMenuEnabled) {
      router.push({
        pathname: "/admin/modules/new",
      });
    } else {
      setShowAddModuleMenu(true);
    }
  }, [isContentMenuEnabled]);

  const onStartWithTemplates = useCallback(() => {
    if (isTemplatesV2Enabled) {
      router.push({
        pathname: "/admin/modules/templates",
      });
      useAnalyticsSDK
        ? viewGoalTemplatePage()
        : sendSegmentEvent(SEGMENT_EVENTS.VIEW_GOAL_TEMPLATE_PAGE);
    }
  }, [isTemplatesV2Enabled]);

  const onChangeTab = useCallback(
    (tab: string) => {
      dispatch(setActiveModuleAction("100000"));
      setTab(tab);

      if (useAnalyticsSDK) {        
        switch (tab) {
          case "header":
            viewHeaderTab()
            break;
          case "theme":
            viewThemeTab()
            break;
          case "social-links":
            viewSocialLinksTab()
            break;
          case "modules":
            viewModuleTab()
            break;
  
          default:
            break;
        }
      }
      else {
        switch (tab) {
          case "header":
            sendSegmentEvent(SEGMENT_EVENTS.VIEW_HEADER_TAB);
            break;
          case "theme":
            sendSegmentEvent(SEGMENT_EVENTS.VIEW_THEME_TAB);
            break;
          case "social-links":
            sendSegmentEvent(SEGMENT_EVENTS.VIEW_SOCIAL_LINKS_TAB);
            break;
          case "modules":
            sendSegmentEvent(SEGMENT_EVENTS.VIEW_MODULES_TAB);
            break;
  
          default:
            break;
        }
      }

      router.replace(adjust(`/${tab}`, isUpcoming));
    },
    [router, sendSegmentEvent]
  );

  const scrollToId = useCallback(
    (id: string) => {
      const scroll = document.querySelector(id);
      scroll?.scrollIntoView({ behavior: "smooth", block: "center" });
    },
    [document]
  );
  const handleReview = useCallback(
    (key: string) => () => {
      if (key === "avatar") {
        onChangeTab("header");
        setTimeout(() => {
          scrollToId("#profile-photo");
        }, 300);
        return;
      }
      if (key === "custom-image") {
        onChangeTab("header");
        setTimeout(() => {
          scrollToId("#profile-display-name");
        }, 300);
        return;
      }
    },
    [modules, scrollToId, onChangeTab]
  );
  const handlePublish = useCallback(() => {
    // trigger Google Tag Manager event
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ event: "publish-profile" });

    const disabledFanClub = modules?.some(
      (el) =>
        el.type === ModuleType.FAN_CLUB &&
        !(el.items[0] as any)?.thumbnail
    );
    const disabledAvatar = !talentProfile?.avatar;
    const disabledCustomPublish =
      talentProfile?.showDisplayName &&
      ((talentProfile?.displayNameType ===
        TalentProfileDisplayNameTypes.IMAGE &&
        !talentProfile.displayNameImage) ||
        (talentProfile?.displayNameType ===
          TalentProfileDisplayNameTypes.TEXT &&
          !talentProfile.displayName));
    const messages = [];
    if (disabledAvatar) {
      messages.push({
        key: "avatar",
        message:
          "Failed to publish. Please review the errors before continuing.",
        onReview: handleReview("avatar"),
      });
    }
    if (disabledCustomPublish) {
      messages.push({
        key: "custom-image",
        message:
          "Failed to publish. Please review the errors before continuing.",
        onReview: handleReview("custom-image"),
      });
    }
    if (disabledFanClub) {
      messages.push({
        key: "fan-club",
        message:
          "Failed to publish. Please review the errors before continuing.",
        onReview: handleReview("fan-club"),
      });
    }
    if (messages.length) {
      notification.showErrorPublish({
        key: "publish-error",
        messages: messages,
      });
      return;
    }
    message.destroy("publish-error");

    if (isTemplatesV2Enabled) {
      showPublishModal();
      return;
    }

    if (
      talentProfile?.localizationActive &&
      talentProfile.localizations?.length
    ) {
      setIsVisiblePublish(true);
      return;
    }
    setVisibleConfirmPublish(true);
  }, [talentProfile, modules]);

  const showPublishModal = useCallback(() => {
    if (
      talentProfile?.localizationActive &&
      talentProfile.localizations?.length
    ) {
      setIsVisiblePublish(true);
      return;
    }
    setVisibleConfirmPublish(true);
  }, [talentProfile, hasTemplateModules, isTemplatesV2Enabled]);

  const renderLoadingAutoSave = useCallback(() => {
    if (!isPublished && loadingAutoSave) {
      return (
        <Col data-testid="profile__autosave">
          {<LoadingOutlined width={17} height={17} />}
          <Text preset="medium16" className={classNames(" m__l--8", "m__r--8")}>
            Saving
          </Text>
        </Col>
      );
    }
    if (!isPublished && isAutoSaveSuccess) {
      return (
        <Col data-testid="profile__autosave">
          <Text preset="medium16" className="m__r--24 m__l--8">
            Saved
          </Text>
        </Col>
      );
    }
    return null;
  }, [isPublished, loadingAutoSave, isAutoSaveSuccess]);

  const renderTab = () => {
    return (
      <>
        <ProfileHeader className={tab === "header" ? "d--block" : "d--none"} />
        <ProfileTheme
          className={tab === "theme" ? "d--block" : "d--none"}
          defaultCustomColor={defaultCustomColor}
          setDefaultCustomColor={setDefaultCustomColor}
          firstThemeType={firstThemeType}
          setFirstThemeType={setFirstThemeType}
        />
        <ProfileSocialLinks
          className={tab === "social-links" ? "d--block" : "d--none"}
        />
        <Card
          className={classNames(
            "border__radius--16 profile-modules",
            tab === "modules" ? "d--block" : "d--none"
          )}
        >
          {user?.talentProfile?.localizationActive && (
            <LocalizationSelect
              value={localizationSelected}
              onChange={handleChangeLocalization}
              setValue={setLocalizationSelected}
            />
          )}
          <div className="p__x--20">
            {moduleLoading ? (
              <div className="text__align--center">
                <Spin />
              </div>
            ) : (
              <IfFeature
                feature={FLAGS.FEAT_SB_358_SHOW_MODULE_MENU_AFTER_NO_TEMPLATE}
                enabled={
                  <ModuleList
                    showMenu={showAddModuleMenu}
                    setShowMenu={setShowAddModuleMenu}
                  />
                }
                disabled={<ModuleList />}
              />
            )}
          </div>
        </Card>
      </>
    );
  };

  const handleClickOnboardingItem = (item: any) => {
    let tab = "header";
    switch (item.key) {
      case "module":
        tab = "modules";
        break;
      case "social":
        tab = "social-links";
        break;
      default:
        break;
    }
    onChangeTab(tab);
    return;
  };

  useEffect(() => {
    if (useAnalyticsSDK) {
      switch (tab) {
        case "header":
          viewHeaderTab()
          break;
        case "theme":
          viewThemeTab()
          break;
        case "social-links":
          viewSocialLinksTab()
          break;
        case "modules":
          viewModuleTab()
          break;
  
        default:
          break;
      }
    }
    else {
      switch (tab) {
        case "header":
          sendSegmentEvent(SEGMENT_EVENTS.VIEW_HEADER_TAB);
          break;
        case "theme":
          sendSegmentEvent(SEGMENT_EVENTS.VIEW_THEME_TAB);
          break;
        case "social-links":
          sendSegmentEvent(SEGMENT_EVENTS.VIEW_SOCIAL_LINKS_TAB);
          break;
        case "modules":
          sendSegmentEvent(SEGMENT_EVENTS.VIEW_MODULES_TAB);
          break;
  
        default:
          break;
      }
    }
  }, [tab]);

  return {
    title,
    isBlockingEditState,
    isPublished,
    isOnModulesPage,
    loading,
    loadingPublish,
    modules,
    disableBody,
    enableBody,
    handleClickOnboardingItem,
    handlePublish,
    onCheckBeforeChangeRouter,
    renderLoadingAutoSave,
    renderTab,
    setDefaultCustomColor,
    setFirstThemeType,
    onStartFromScratch,
    onStartWithTemplates,
  };
};

export default Profile;
