import Button from "antd/lib/button";
import { Col, Row } from "antd/lib/grid";
import DragDropContext from "components/DragDropContext";
import { Icon } from "components/Icon";
import PortalComponent from "components/PortalComponent/PortalComponent";
import ProductCardModule from "components/ProductCardModule";
import ProductEditorModal from "components/ProductEditorModal/ProductEditorModal";
import { Text } from "components/Typography";
import { SEGMENT_EVENTS } from "constants/segment";
import { useAnalytics } from "hooks/useAnalytics";
import { useModules } from "hooks/useModules";
import {
  BaseItem,
  ProductItem,
  TalentProfileModule,
} from "models/talent/talent-profile-module.model";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
import { Product } from "redux/Product/types";
import { useTypedSelector } from "redux/rootReducer";
import { selectLocalizationSelected } from "redux/User/selector";
import { ArrayServices } from "utils/array";
import {
  flipVisibilityForItemAndCloneArray,
  isEmptyModule,
} from "utils/modules";
import ModuleEditor from "../ModuleEditor";
import EmptyModule from "./EmptyModule";
import "./ModuleProduct.scss";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { useWindowSize } from "../../../hooks";
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";
import { trackingProps } from "utils/tracking";

const ProductCardMemo = React.memo(ProductCardModule);

interface ModuleProductProps {
  module: TalentProfileModule<ProductItem>;
  dragHandleProps?: DraggableProvidedDragHandleProps;
  active: boolean;
}

const ModuleProduct: React.FC<ModuleProductProps> = ({
  module,
  dragHandleProps,
  active,
}) => {
  const { sendSegmentEvent } = useAnalytics();
  const profileContext = useModules();
  const [productList, setProductList] = useState<ProductItem[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [productEditState, setProductEditState] = useState<{
    isEdit: boolean;
    product?: ProductItem;
    productEditIndex?: number;
  }>({
    isEdit: false,
  });
  const localizationSelected = useTypedSelector(selectLocalizationSelected);
  const { width } = useWindowSize();
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED);

  const isMobileStyleChangesEnabled = width && width <= 768;

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

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

  const onAddProduct = useCallback(() => {
    setProductEditState((preState) => ({
      ...preState,
      isEdit: false,
      product: undefined,
      productIndex: undefined,
    }));
    setShowModal(true);
  }, []);

  const onEditProduct = useCallback((product: Product) => {
    setProductEditState((preState) => ({
      ...preState,
      isEdit: true,
      product: product,
      productIndex: product.index,
    }));
    setShowModal(true);
  }, []);

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

  const onSaveProductCallback = useCallback(
    (product: ProductItem) => {
      let moduleEdit;
      if (productEditState.isEdit) {
        moduleEdit = {
          ...module,
          items: ArrayServices.updateWithIndex(
            module.items,
            product.order as number,
            product
          ),
          isUpdate: true,
        };
      } else {
        moduleEdit = {
          ...module,
          items: ArrayServices.unshift(module.items, product),
          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, productEditState, localizationSelected, profileContext.setModule]
  );

  const onDropEndProducts = useCallback(
    (list: ProductItem[]) => {
      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}>
        <ProductEditorModal
          isEdit={productEditState.isEdit}
          product={productEditState.product}
          show={showModal}
          toggleModal={onToggleModal}
          onConfirmCallback={onSaveProductCallback}
        />
        {isEmptyModule(module) ? (
          <React.Fragment>
            <EmptyModule titleAction="Add New Product" onClick={onAddProduct} />
          </React.Fragment>
        ) : (
          <React.Fragment>
            <Row
              align="middle"
              justify="space-between"
              className={isMobileStyleChangesEnabled ? "m__b--8" : "m__b--22"}
            >
              <Col>
                <Button
                  className="add-product-btn p--0"
                  type="link"
                  onClick={onAddProduct}
                >
                  <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 Product
                    </Text>
                  </div>
                </Button>
              </Col>
              <Col>
                <Text preset="medium14" className="text--default opacity-6">
                  {productList.length}&nbsp;
                  {productList.length > 1 ? "products added" : "product added"}
                </Text>
              </Col>
            </Row>

            <DragDropContext
              droppableId="product-child-drop"
              listClassName="product-list"
              itemIdPrefix="product"
              direction="vertical"
              list={productList}
              onDropEndCallback={onDropEndProducts}
            >
              {(dragProvided, snapshot, item, productIndex) => {
                const isRender = active ? active : productIndex < 2;

                return isRender ? (
                  <PortalComponent
                    innerRef={dragProvided.innerRef}
                    key={productIndex}
                    namespaceClass="product-list"
                    provided={dragProvided}
                    snapshot={snapshot}
                    single={productList?.length === 1}
                  >
                    <ProductCardMemo
                      disableDragDrop={module.items.length <= 1}
                      index={productIndex}
                      item={item}
                      showPrice
                      showStatus={false}
                      onEdit={onEditProduct}
                      onDelete={onDeleteProduct}
                      dragHandleProps={dragProvided.dragHandleProps}
                      titleShortcut={true}
                      module={module}
                    />
                  </PortalComponent>
                ) : (
                  <></>
                );
              }}
            </DragDropContext>
            {!active && productList.length > 2 && (
              <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
                <Text preset="medium14" className="opacity-6">
                  +{productList.length - 2} More
                </Text>
              </div>
            )}
          </React.Fragment>
        )}
      </ModuleEditor>
    </React.Fragment>
  );
};

export default React.memo(ModuleProduct);
