import { Button, Col, Row, Tooltip } from "antd";
import classNames from "classnames";
import ConfirmDeleteModal from "components/ConfirmDeleteModal";
import { Icon } from "components/Icon";
import PopoverMenu from "components/PopoverMenu";
import { Paragraph } from "components/Typography";
import { useModules } from "hooks/useModules";
import reduce from "lodash/reduce";
import uniqBy from "lodash/uniqBy";
import {
  TalentModuleMixItem,
  TalentProfileModule,
} from "models/talent/talent-profile-module.model";
import * as React from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import "./GroupModuleMenu.scss";
import { useWindowSize } from "../../hooks";
import { ModuleType } from "@komi-app/shared-types"

enum WARING_STATUS {
  DELETE = "DELETE",
  UN_GROUP = "UN_GROUP",
}
const GroupModuleMenu = () => {
  const [visibleTooltip, setVisibleTooltip] = useState(false);
  const [visiblePopover, setVisiblePopover] = useState(false);
  const [warningStatus, setWarningStatus] = useState({
    status: WARING_STATUS.DELETE,
    visible: false,
  });

  const { width } = useWindowSize();
  const isModuleGroupingDisabled = width && width <= 768;

  const {
    selectedModules,
    setSelectedModules,
    onGrouping,
    onUnGroup,
    onMoveGroup,
    modules,
    removeSelectedModules,
  } = useModules();

  const isUnGrouping = useMemo(() => {
    if (
      selectedModules.every(
        (item: TalentProfileModule<TalentModuleMixItem>) => !item.groupId
      )
    ) {
      return false;
    }
    if (uniqBy(selectedModules, "groupId").length === 1) {
      return true;
    }
    return false;
  }, [selectedModules]);
  const isDisabled = useMemo(
    () => selectedModules.length === 1 && !isUnGrouping,
    [isUnGrouping, selectedModules]
  );

  const groups = useMemo(() => {
    return reduce(
      modules,
      (results: any, item) => {
        if (
          item.type === ModuleType.GROUP &&
          !selectedModules.some((el: any) => el.groupId === item.id)
        ) {
          return [
            ...results,
            {
              key: item.id,
              label: item.name,
              onClick: onMoveGroup(item),
            },
          ];
        }
        return results;
      },
      []
    );
  }, [modules, selectedModules, onMoveGroup]);

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollY = window.scrollY;
      if (currentScrollY < 6) {
        return;
      }
      setVisibleTooltip(false);
      setVisiblePopover(false);
    };
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);
  const onClose = useCallback(() => {
    setSelectedModules?.([]);
  }, []);

  const handleGroup = () => {
    if (isDisabled) {
      return;
    }
    if (!isUnGrouping) {
      onGrouping();
      return;
    }
    setWarningStatus({
      status: WARING_STATUS.UN_GROUP,
      visible: true,
    });
  };
  const onWarningConfirm = useCallback(() => {
    if (warningStatus.status === WARING_STATUS.DELETE) {
      removeSelectedModules();
      setWarningStatus({
        status: WARING_STATUS.DELETE,
        visible: false,
      });
      return;
    }
    onUnGroup(selectedModules);
    setWarningStatus({
      status: WARING_STATUS.DELETE,
      visible: false,
    });
  }, [removeSelectedModules, selectedModules, warningStatus, onUnGroup]);
  const onDeleteClick = useCallback(() => {
    setWarningStatus({
      status: WARING_STATUS.DELETE,
      visible: true,
    });
  }, []);
  const warningData = useMemo(() => {
    if (warningStatus.status === WARING_STATUS.DELETE) {
      return {
        title: `Are you sure you want to delete the selected module${selectedModules.length > 1 ? "s" : ""
          }?`,
        description:
          selectedModules.length > 1
            ? `The modules will be deleted and you can’t undo this action.
        If any of your modules have captured data, don’t worry, your data won’t be removed and will still be accessible on the Data Export page.`
            : `The module will be deleted and you can’t undo this action.
        If the module has captured data, don’t worry, your data won’t be removed and will still be accessible on the Data Export page.`,
      };
    }
    return {
      title: `Are you sure you want to ungroup these module${selectedModules.length > 1 ? "s" : ""
        }?`,
      description: `The modules will be ungrouped and displayed individually. You can group them again at any time.`,
    };
  }, [warningStatus, selectedModules]);
  return (
    <>
      {!!selectedModules.length && !isModuleGroupingDisabled && (
        <Row align="middle" className="group-module-menu">
          <Col flex="1">
            <Row gutter={32} align="middle">
              <Col>
                <Paragraph preset="semibold16" className="text--white p__y--18">
                  {`${selectedModules.length} Module${selectedModules.length > 1 ? "s" : ""
                    } Selected`}
                </Paragraph>
              </Col>
              <Col>
                <div className="divider-vertical height--24" />
              </Col>
              <Col>
                <Tooltip
                  style={{ zIndex: 9999999 }}
                  visible={isUnGrouping ? false : visibleTooltip}
                  onVisibleChange={setVisibleTooltip}
                  overlayClassName="group-module-tooltip"
                  placement="top"
                  title={`Group modules together into sections`}
                >
                  <Button
                    onClick={handleGroup}
                    className={classNames("p__x--0 p__y--18", {
                      "opacity--05": isDisabled,
                    })}
                    type="text"
                    data-testid="group-module-menu--handleGroup"
                  >
                    <Row gutter={4} align="middle">
                      <Col className="height--24">
                        <Icon
                          name={isUnGrouping ? "un-grouping" : "grouping"}
                        />
                      </Col>
                      <Col>
                        <Paragraph preset="semibold16" className="text--white">
                          {isUnGrouping ? "Ungroup Modules" : "Group Modules"}
                        </Paragraph>
                      </Col>
                    </Row>
                  </Button>
                </Tooltip>
              </Col>
              {!!groups.length && (
                <Col>
                  <PopoverMenu
                    visible={visiblePopover}
                    onChangeVisible={setVisiblePopover}
                    data={groups}
                    title="Module Groups"
                  >
                    <Button className="p__x--0 p__y--18" type="text">
                      <Row gutter={4} align="middle">
                        <Col className="height--24">
                          <Icon name="move-to" />
                        </Col>
                        <Col>
                          <Paragraph
                            preset="semibold16"
                            className="text--white"
                          >
                            Move to
                          </Paragraph>
                        </Col>
                      </Row>
                    </Button>
                  </PopoverMenu>
                </Col>
              )}
              <Col>
                <Button
                  onClick={onDeleteClick}
                  className="p__x--0 p__y--18"
                  type="text"
                  data-testid="group-module-menu-delete-button"
                >
                  <Row gutter={4} align="middle">
                    <Col className="text--white height--24">
                      <Icon name="trash" />
                    </Col>
                    <Col>
                      <Paragraph preset="semibold16" className="text--white">
                        Delete
                      </Paragraph>
                    </Col>
                  </Row>
                </Button>
              </Col>
            </Row>
          </Col>
          <Col className="height--28 m__l--32">
            <Button onClick={onClose} type="text" className="p--0">
              <Icon width={28} height={28} name="close-white" />
            </Button>
          </Col>
        </Row>
      )}
      <ConfirmDeleteModal
        show={warningStatus.visible}
        toggleModal={() =>
          setWarningStatus({
            status: WARING_STATUS.DELETE,
            visible: false,
          })
        }
        cancelLabel="No Thanks!"
        confirmLabel={
          warningStatus.status === WARING_STATUS.DELETE ? "Delete" : "Ungroup"
        }
        width={522}
        title={warningData.title}
        description={warningData.description}
        handleConfirm={onWarningConfirm}
      />
    </>
  );
};

export default GroupModuleMenu;
