import { Col, Dropdown, Menu, Row } from "antd";
import classNames from "classnames";
import { Icon } from "components/Icon";
import { Paragraph, Text } from "components/Typography";
import { SEGMENT_EVENTS } from "constants/segment";
import { useAnalytics } from "hooks/useAnalytics";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { selectLocalizationSelected } from "redux/User/selector";
import { useTypedSelector } from "redux/rootReducer";
import "./AddFieldsMenu.scss";
import { DataCaptureFieldType } from "@komi-app/shared-types"
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";
import { DEFAULT_UUID } from "@komi-app/profiles-sdk";

const ListMenuModule = [
  {
    title: "Text Field",
    icon: <Icon width={24} height={24} name="capture-text-field" />,
    key: "text-field",
    subMenu: [
      {
        title: "Short Answer",
        icon: <Icon name="capture-text-field" width={24} height={24} />,
        type: DataCaptureFieldType.INPUT,
      },
      {
        title: "Paragraph",
        icon: <Icon width={24} height={24} name="capture-paragraph" />,
        type: DataCaptureFieldType.TEXTAREA,
      },
    ],
  },
  {
    title: "Contact Info",
    icon: <Icon width={24} height={24} name="capture-contact-info" />,
    key: "contact-info",
    subMenu: [
      {
        title: "Phone Number",
        icon: <Icon name="capture-phone" width={24} height={24} />,
        type: DataCaptureFieldType.PHONE_NUMBER,
      },
      {
        title: "Email Address",
        icon: <Icon width={24} height={24} name="capture-email" />,
        type: DataCaptureFieldType.EMAIL_ADDRESS,
      },
    ],
  },
  {
    title: "Selection",
    icon: <Icon name="capture-selection" width={24} height={24} />,
    key: "selection",
    subMenu: [
      {
        title: "Single Choice",
        icon: <Icon width={24} height={24} name="capture-single-choice" />,
        type: DataCaptureFieldType.SELECT_SINGLE,
      },
      {
        title: "Multiple Choice",
        icon: <Icon width={24} height={24} name="capture-mutil-choice" />,
        type: DataCaptureFieldType.SELECT_MULTIPLE,
      },
      {
        title: "Country Dropdown",
        icon: <Icon width={24} height={24} name="capture-global" />,
        type: DataCaptureFieldType.SELECT_COUNTRY,
      },
      {
        title: "Date Selection",
        icon: <Icon width={24} height={24} name="capture-calendar" />,
        type: DataCaptureFieldType.SELECT_DATE,
      },
    ],
  },
  {
    key: "legals",
    title: "Legals",
    icon: <Icon width={24} height={24} name="capture-legals" />,
    type: DataCaptureFieldType.LEGALS,
  },
];
interface AddFieldsMenuProps {
  onAddItem?: (key: DataCaptureFieldType) => void;
}
const AddFieldsMenu: React.FC<AddFieldsMenuProps> = ({ onAddItem }) => {
  const [showMenu, setShowMenu] = useState(false);
  const localizationSelected = useTypedSelector(selectLocalizationSelected);
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking()
  const openModuleCreationMenu = createTracker(CreatorEvent.OPEN_MODULE_CREATION_MENU)

  const handleScroll = useCallback(() => {
    showMenu && setShowMenu(false);
  }, [showMenu, setShowMenu]);

  const { sendSegmentEvent } = useAnalytics();

  useEffect(() => {
    if (showMenu) {
      window.addEventListener("scroll", handleScroll);
      return () => window.removeEventListener("scroll", handleScroll);
    }
  }, [showMenu]);

  const addModule = useCallback(
    (menu: any) => () => {
      setShowMenu(false);
      onAddItem?.(menu.type);
    },
    [onAddItem]
  );

  const menu = useMemo(() => {
    return (
      <Menu
        className={classNames("add-field-menu__menu")}
        style={{ width: 270 }}
        triggerSubMenuAction={"click"}
      >
        {ListMenuModule?.map((item) => {
          if (!item.subMenu) {
            return (
              <Menu.Item key={item.key} onClick={addModule(item)}>
                <Row gutter={16} align="middle">
                  <Col className="height--24">{item.icon}</Col>
                  <Col>
                    <Paragraph preset="semibold16">{item.title}</Paragraph>
                  </Col>
                </Row>
              </Menu.Item>
            );
          }
          return (
            <Menu.SubMenu
              popupClassName={classNames("add-field-menu__sub-menu")}
              key={item.key}
              title={item.title}
              icon={<div className="height--24 m__r--16">{item.icon}</div>}
            >
              {item.subMenu.map((el: any) => (
                <Menu.Item
                  onClick={addModule(el)}
                  key={String(el.type).toLowerCase()}
                >
                  <Row gutter={16} align="middle">
                    <Col className="height--24">{el.icon}</Col>
                    <Col>
                      <Paragraph preset="semibold16">{el.title}</Paragraph>
                    </Col>
                  </Row>
                </Menu.Item>
              ))}
            </Menu.SubMenu>
          );
        })}
      </Menu>
    );
  }, [ListMenuModule, addModule]);

  const onVisibleChange = (visible: boolean) => {
    setShowMenu(visible);
    if (visible) {
      const pageId = localizationSelected?.id || DEFAULT_UUID
      const pageName = localizationSelected?.name || "Default"
      useAnalyticsSDK
        ? openModuleCreationMenu({
          pageId,
          pageName
        })
        : sendSegmentEvent(SEGMENT_EVENTS.OPEN_MODULE_CREATION_MENU, {
          "Page ID": pageId,
          "Page Name": pageName,
        });
    }
  };

  return (
    <React.Fragment>
      <div className="add-field-menu">
        <Dropdown
          visible={showMenu}
          placement="topLeft"
          onVisibleChange={onVisibleChange}
          overlay={menu}
          overlayClassName="add-field-menu__dropdown"
          trigger={["click"]}
        >
          <Row gutter={4} align="middle" className="cursor-pointer">
            <Col className="height--32">
              <Icon name="add-blue" />
            </Col>
            <Col>
              <Text preset="semibold18" className="text--blue">
                Add a Field
              </Text>
            </Col>
          </Row>
        </Dropdown>
      </div>
    </React.Fragment>
  );
};

export default AddFieldsMenu;
