import React from 'react';
// import { notification } from 'antd';
import { useRecoilState } from 'recoil';
import {
  IVector3,
  ComponentTypeEnum,
  FlowFenceTemplate,
  EventName,
  FlowFenceComponent,
} from '@easytwin/core';

import { ProButton } from '@/components';
import {
  _currentScene,
  _currentComponentDetail,
  _scenePickPositionModeOpen,
  _sceneObjectCreateModeOpen,
  _sceneObjectEditModeOpen,
} from '../../module';

export interface TemplateToolProp {
  className?: string;
  onPickPosition?: (position: IVector3) => void;
  onPickPositions?: (positions: IVector3[]) => void;
}

const TemplateTool: React.FC<TemplateToolProp> = function ({
  className,
  onPickPosition,
  onPickPositions,
}) {
  const [visible, setVisible] = React.useState<boolean>(false);
  const [templateVisible, setTemplateVisible] = React.useState<boolean>(false);
  const [childVisible, setChildVisible] = React.useState<boolean>(false);

  const [currentScene] = useRecoilState(_currentScene);
  const [currentComponentDetail] = useRecoilState(_currentComponentDetail);

  const [pickPositionModeOpen, setPickPositionModeOpen] = useRecoilState(
    _scenePickPositionModeOpen,
  );
  const [sceneObjectCreateModeOpen, setSceneObjectCreateModeOpen] = useRecoilState(
    _sceneObjectCreateModeOpen,
  );
  const [sceneObjectEditModeOpen, setSceneObjectEditModeOpen] =
    useRecoilState(_sceneObjectEditModeOpen);

  React.useEffect(() => {
    setVisible(false);
    setTemplateVisible(false);
    setChildVisible(false);
    setPickPositionModeOpen(false);
    setSceneObjectCreateModeOpen(false);
    setSceneObjectEditModeOpen(false);

    if (
      currentComponentDetail &&
      currentComponentDetail.commonConfig?.isGroup &&
      currentComponentDetail.type !== ComponentTypeEnum.BIZGROUP
    ) {
      setVisible(true);
      setTemplateVisible(true);
    }

    if (
      currentComponentDetail &&
      !currentComponentDetail.commonConfig?.isGroup &&
      currentComponentDetail.type === ComponentTypeEnum.FENCE
    ) {
      setVisible(true);
      setChildVisible(true);
    }

    return () => {
      setVisible(false);
      setTemplateVisible(false);
      setChildVisible(false);
      setPickPositionModeOpen(false);
      setSceneObjectCreateModeOpen(false);
      setSceneObjectEditModeOpen(false);
    };
  }, [
    currentComponentDetail,
    setPickPositionModeOpen,
    setSceneObjectCreateModeOpen,
    setSceneObjectEditModeOpen,
  ]);

  React.useEffect(() => {
    if (!currentScene) return;

    const viewpoint = currentScene.getViewport();

    if (pickPositionModeOpen) {
      viewpoint.templateController.pickPositionHelper.startPick((param) =>
        onPickPosition?.(param.point),
      );
      // notification.success({
      //   message: '母版新建',
      //   description: '已进入新建模式，可通过鼠标在场景内点击拾取位置。',
      //   placement: 'bottomRight',
      // });
    }

    if (sceneObjectCreateModeOpen) {
      if (!currentComponentDetail) return;

      // const template = viewpoint.templateController.getTemplate<FlowFenceTemplate>(currentComponentDetail.id);
      const template = viewpoint.componentMap.get(currentComponentDetail.id) as
        | FlowFenceComponent
        | undefined;
      if (!template) return;

      const id = 'drawingFence';

      template.startDraw({
        onCompleteCreate: (anchor) => {
          anchor && onPickPositions?.(anchor.getPoints());
          // template.remove(id);
        },
      });
      // 监听完成时间，隐藏图标
      template.addEventListener(EventName.Template.FenceCreateEnd, handleOutCreateMode);
    }

    return () => {
      if (pickPositionModeOpen) {
        viewpoint.templateController.pickPositionHelper.endPick();
      }

      if (sceneObjectCreateModeOpen) {
        if (!currentComponentDetail) return;

        // const template = viewpoint.templateController.getTemplate<FlowFenceTemplate>(currentComponentDetail.id);
        const template = viewpoint.componentMap.get(currentComponentDetail.id) as
          | FlowFenceComponent
          | undefined;
        if (!template) return;
        template.removeEventListener(EventName.Template.FenceCreateEnd, handleOutCreateMode);
        template.endDraw();
      }
    };
  }, [
    currentScene,
    currentComponentDetail,
    pickPositionModeOpen,
    sceneObjectCreateModeOpen,
    onPickPosition,
    onPickPositions,
  ]);

  const handleInCreateMode = () => {
    if (!currentComponentDetail || !currentComponentDetail.commonConfig?.isGroup) return;

    if (
      currentComponentDetail.type === ComponentTypeEnum.POINT ||
      currentComponentDetail.type === ComponentTypeEnum.POIPANNEL ||
      currentComponentDetail.type === ComponentTypeEnum.POIIFRAME
    )
      setPickPositionModeOpen(true);

    if (currentComponentDetail.type === ComponentTypeEnum.FENCE) setSceneObjectCreateModeOpen(true);
  };

  const handleOutCreateMode = () => {
    setPickPositionModeOpen(false);
    setSceneObjectCreateModeOpen(false);
    setSceneObjectEditModeOpen(false);
  };

  return visible ? (
    <div className={className}>
      {templateVisible ? (
        !pickPositionModeOpen && !sceneObjectCreateModeOpen ? (
          <ProButton className="flex-1" type="primary" onClick={handleInCreateMode}>
            进入新建模式
          </ProButton>
        ) : (
          <ProButton className="flex-1" type="primary" onClick={handleOutCreateMode}>
            完成新建
          </ProButton>
        )
      ) : null}

      {childVisible ? (
        sceneObjectEditModeOpen ? (
          <ProButton
            className="flex-1"
            type="primary"
            onClick={() => setSceneObjectEditModeOpen(false)}>
            保存并退出编辑模式
          </ProButton>
        ) : (
          <ProButton
            className="flex-1"
            type="primary"
            onClick={() => setSceneObjectEditModeOpen(true)}>
            进入编辑模式
          </ProButton>
        )
      ) : null}
    </div>
  ) : null;
};

export default TemplateTool;
