import { Col } from "antd";
import DragDropContext from "components/DragDropContext";
import LoadingModule from "components/LoadingModule";
import PortalComponent from "components/PortalComponent/PortalComponent";
import { Text } from "components/Typography";
import { SEGMENT_EVENTS } from "constants/segment";
import { useAnalytics } from "hooks/useAnalytics";
import { useModules } from "hooks/useModules";
import {
  BandsintownItem,
  TalentProfileModule,
} from "models/talent/talent-profile-module.model";
import React, { useCallback, useMemo, useState } from "react";
import { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
import { useTypedSelector } from "redux/rootReducer";
import { selectLocalizationSelected } from "redux/User/selector";
import { ArrayServices } from "utils/array";
import BandsintownEditorModal from "../../../components/BandsintownEditorModal";
import BandsintownEventCard from "../../../components/BandsintownEventCard";
import { Icon } from "../../../components/Icon";
import { Paragraph } from "../../../components/Typography";
import ModuleEditor from "../ModuleEditor";
import "./ModuleBandsintown.scss";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";
import { trackingProps } from "utils/tracking";

const BandsintownEventCardMemo = React.memo(BandsintownEventCard);

interface ModuleBandsintownProps {
  module: TalentProfileModule<BandsintownItem>;
  dragHandleProps?: DraggableProvidedDragHandleProps;
  active: boolean;
}

const ModuleBandsintown: React.FC<ModuleBandsintownProps> = ({
  module,
  dragHandleProps,
  active,
}) => {
  const { sendSegmentEvent } = useAnalytics();
  const profileContext = useModules();
  const localizationSelected = useTypedSelector(selectLocalizationSelected);
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED);

  const item = useMemo(() => {
    return module.items[0];
  }, [module.items]);
  const [showModal, setShowModal] = useState(false);

  const { loadingShop, thirdPartyData } = profileContext;
  const loading = useMemo(() => {
    return loadingShop.some((key: string) => key === module.id);
  }, [loadingShop, module.id]);
  const data = useMemo(() => {
    return thirdPartyData.find((item: any) => item.id === module.id);
  }, [thirdPartyData, module.id]);
  const events = useMemo(() => data?.events || [], [data]);

  const onEditBandsintownLink = useCallback(() => {
    setShowModal(true);
  }, []);

  const onSaveLinkCallback = useCallback(
    (link: BandsintownItem) => {
      const moduleEdit = {
        ...module,
        items: ArrayServices.updateWithIndex(module.items, 0, link),
        isUpdate: true,
      };
      profileContext.setModule(moduleEdit);

      const {
        pageId,
        pageName,
        type
      } = trackingProps(moduleEdit.type, localizationSelected)

      useAnalyticsSDK
        ? elementCreate({ pageId, pageName, type })
        : sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
            "Module Type": moduleEdit.type,
            "Page ID": localizationSelected?.id || null,
            "Page Name": localizationSelected?.name || "Default",
          });
      onToggleModal(false);
    },
    [module, localizationSelected, profileContext.setModule, sendSegmentEvent]
  );

  const onDropEndLinks = useCallback(
    (list: BandsintownItem[]) => {
      profileContext.setModule({
        ...module,
        items: list.map((item, index) => ({ ...item, order: index })),
        isUpdate: true,
      });
    },
    [module, profileContext]
  );

  const onToggleModal = useCallback((value: boolean) => {
    setShowModal(value);
  }, []);

  const renderContent = () => {
    if (loading) {
      return <LoadingModule />;
    }
    if (!events.length) {
      return (
        <React.Fragment>
          <Col span={24} className="text__align--center">
            <Icon name="empty-module" />
          </Col>
          <Col span={24} className="text__align--center">
            <Paragraph preset="semibold18" className="d--block m__b--4">
              No Events Found
            </Paragraph>
            <Paragraph
              preset="regular16"
              className="d--block subtitle-empty-bandsintown"
            >
              You appear to have no events listed on Bandsintown right now,
              please add some and then refresh the page
            </Paragraph>
          </Col>
        </React.Fragment>
      );
    }
    return (
      <React.Fragment>
        <div className="d--flex justify__content--end align__items--center m__b--22">
          <Text preset="medium14" className="opacity-6">
            {events.length}&nbsp;
            {events.length > 1 ? "dates added" : "date added"}
          </Text>
        </div>
        <DragDropContext
          droppableId="link-child-drop"
          listClassName="product-list"
          itemIdPrefix="link"
          direction="vertical"
          list={events}
          onDropEndCallback={onDropEndLinks}
        >
          {(dragProvided, snapshot, item, linkIndex) => {
            const isRender = active ? active : linkIndex < 2;
            return isRender ? (
              <PortalComponent
                key={linkIndex}
                innerRef={dragProvided.innerRef}
                namespaceClass="product-list"
                provided={dragProvided}
                snapshot={snapshot}
                single={events?.length === 1}
              >
                <BandsintownEventCardMemo
                  index={linkIndex}
                  titleShortcut
                  item={item as any}
                  dragHandleProps={dragProvided.dragHandleProps}
                />
              </PortalComponent>
            ) : (
              <></>
            );
          }}
        </DragDropContext>
        {!active && events.length > 2 && (
          <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
            <Text preset="medium14" className="opacity-6">
              +{events.length - 2} More
            </Text>
          </div>
        )}
      </React.Fragment>
    );
  };
  return (
    <React.Fragment>
      <ModuleEditor
        module={module}
        dragHandleProps={dragHandleProps}
        onEditBandsintownLink={onEditBandsintownLink}
      >
        <BandsintownEditorModal
          isEdit={true}
          item={item}
          visible={showModal}
          onChangeVisible={onToggleModal}
          onConfirmCallback={onSaveLinkCallback}
        />
        {renderContent()}
      </ModuleEditor>
    </React.Fragment>
  );
};

export default React.memo(ModuleBandsintown);
