import Button from "antd/lib/button";
import DragDropContext from "components/DragDropContext";
import { Icon } from "components/Icon";
import LinkCardModule from "components/LinkCardModule";
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 {
  BaseItem,
  LinkItem,
  TalentProfileModule,
} from "models/talent/talent-profile-module.model";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
import { BaseModuleProps } from "redux/Common/types";
import { useTypedSelector } from "redux/rootReducer";
import { selectLocalizationSelected } from "redux/User/selector";
import { ArrayServices } from "utils/array";
import {
  flipVisibilityForItemAndCloneArray,
  isEmptyModule,
} from "utils/modules";
import LinkEditorModal from "../../../components/LinkEditorModal/LinkEditorModal";
import ModuleEditor from "../ModuleEditor";
import EmptyModule from "./EmptyModule";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";
import { trackingProps } from "utils/tracking";

const LinkCardMemo = React.memo(LinkCardModule);

interface ModuleLinkProps {
  module: TalentProfileModule<LinkItem>;
  dragHandleProps?: DraggableProvidedDragHandleProps;
  active: boolean;
}

const ModuleLink: React.FC<ModuleLinkProps> = ({
  module,
  dragHandleProps,
  active,
}) => {
  const { sendSegmentEvent } = useAnalytics();
  const profileContext = useModules();
  const [linkList, setLinkList] = useState<LinkItem[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [linkEditState, setLinkEditState] = useState<{
    isEdit: boolean;
    link?: LinkItem;
    linkEditIndex?: number;
  }>({
    isEdit: false,
  });
  const localizationSelected = useTypedSelector(selectLocalizationSelected);
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED);

  useEffect(() => {
    setLinkList(
      module.items.map((link, index) => ({
        ...link,
        order: index,
      }))
    );
    return () => {};
  }, [module.items, module.visible]);

  const onEditModuleCallback = useCallback(
    (moduleEdit: TalentProfileModule<LinkItem>) => {
      profileContext.setModule(moduleEdit);
    },
    [profileContext.setModule]
  );

  const onAddLink = useCallback(() => {
    setLinkEditState((preState) => ({
      ...preState,
      isEdit: false,
      link: undefined,
      linkIndex: undefined,
    }));
    setShowModal(true);
  }, []);

  const onEditLink = useCallback((link: LinkItem) => {
    setLinkEditState((preState) => ({
      ...preState,
      isEdit: true,
      link: link,
      linkIndex: link.order,
    }));
    setShowModal(true);
  }, []);

  const onDeleteLink = useCallback(
    (link: LinkItem) => {
      profileContext.setModule({
        ...module,
        items: ArrayServices.removeWithIndex(
          module.items,
          link.order as number
        ),
        isUpdate: true,
      });
    },
    [module, profileContext.setModule]
  );

  const onSaveLinkCallback = useCallback(
    (link: LinkItem) => {
      onToggleModal(false);
      let moduleEdit;
      if (linkEditState.isEdit) {
        moduleEdit = {
          ...module,
          items: ArrayServices.updateWithIndex(
            module.items,
            link.order as number,
            link
          ),
          isUpdate: true,
        };
      } else {
        moduleEdit = {
          ...module,
          items: ArrayServices.unshift(module.items, link),
          isUpdate: true,
        };
      }
      profileContext.setModule(moduleEdit);
      if (!linkEditState.isEdit) {
        const {
          pageId,
          pageName,
          type
        } = trackingProps(
          link.specialOffer?.storeUrl
                ? "SPECIAL OFFER"
                : moduleEdit.type
          ,localizationSelected
        )

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

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

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

  return (
    <React.Fragment>
      <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
        <LinkEditorModal
          isEdit={linkEditState.isEdit}
          link={linkEditState.link}
          show={showModal}
          toggleModal={onToggleModal}
          onConfirmCallback={onSaveLinkCallback}
        />
        {isEmptyModule(module) ? (
          <React.Fragment>
            <EmptyModule titleAction="Add New Link" onClick={onAddLink} />
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div className="d--flex justify__content--between align__items--center m__b--22">
              <Button
                className="add-item-btn p--0"
                type="link"
                onClick={onAddLink}
              >
                <div className="d--flex justify__content--center align__items--center">
                  <Icon name="add-blue" />
                  <Text preset="semibold18" className="text--blue m__l--4">
                    Add New Link
                  </Text>
                </div>
              </Button>
              <Text preset="medium14" className="text--default opacity-6">
                {linkList.length}&nbsp;
                {linkList.length > 1 ? "links added" : "link added"}
              </Text>
            </div>

            <DragDropContext
              droppableId="link-child-drop"
              listClassName="product-list"
              itemIdPrefix="link"
              direction="vertical"
              list={linkList}
              onDropEndCallback={onDropEndLinks}
            >
              {(dragProvided, snapshot, item, linkIndex) => {
                return active ? (
                  <PortalComponent
                    innerRef={dragProvided.innerRef}
                    key={linkIndex}
                    namespaceClass="product-list"
                    provided={dragProvided}
                    snapshot={snapshot}
                    single={linkList?.length === 1}
                  >
                    <LinkCardMemo
                      titleShortcut
                      index={linkIndex}
                      disableDrag={linkList?.length === 1}
                      item={item}
                      onEdit={onEditLink}
                      onDelete={onDeleteLink}
                      dragHandleProps={dragProvided.dragHandleProps}
                      module={module}
                    />
                  </PortalComponent>
                ) : linkIndex < 2 ? (
                  <PortalComponent
                    innerRef={dragProvided.innerRef}
                    key={linkIndex}
                    namespaceClass="product-list"
                    provided={dragProvided}
                    snapshot={snapshot}
                    single={linkList?.length === 1}
                  >
                    <LinkCardMemo
                      titleShortcut
                      index={linkIndex}
                      disableDrag={linkList?.length === 1}
                      item={item}
                      onEdit={onEditLink}
                      onDelete={onDeleteLink}
                      dragHandleProps={dragProvided.dragHandleProps}
                      module={module}
                    />
                  </PortalComponent>
                ) : (
                  <></>
                );
              }}
            </DragDropContext>
            {!active && linkList.length > 2 && (
              <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
                <Text preset="medium14" className="opacity-6">
                  +{linkList.length - 2} More
                </Text>
              </div>
            )}
          </React.Fragment>
        )}
      </ModuleEditor>
    </React.Fragment>
  );
};

export default React.memo(ModuleLink);
