import React, { useCallback, useEffect, useState } from 'react';
import { useRecoilState } from 'recoil';

import { IVector3 } from '@easytwin/core';

import { ProButton } from '@/components';
import { _sceneBatchModelModeOpen , _currentScene, _currentComponentDetail } from '../../module';



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

function BatchModelTool({ className, onPickPositions }: BatchModelToolProp) {
  const [positions, setPositions] = useState<IVector3[]>([]);

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

  const [sceneObjectEditModeOpen, setSceneObjectEditModeOpen] =
    useRecoilState(_sceneBatchModelModeOpen);

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

    const viewpoint = currentScene.getViewport();

    if (sceneObjectEditModeOpen) {
      viewpoint.templateController.pickPositionHelper.startPick((param) => {
        setPositions((positions) => [...positions, param.point]);
      });
    }

    return () => {};
  }, [sceneObjectEditModeOpen, currentScene]);

  useEffect(() => {
    if (!currentComponentDetail && positions.length === 2) {
      onPickPositions?.(positions);
    } else {
    }
  }, [positions, currentComponentDetail, onPickPositions]);

  const handleOutCreateMode = useCallback(() => {
    setSceneObjectEditModeOpen(false);
  }, []);

  return sceneObjectEditModeOpen ? (
    <div
      className={className}
      style={{
        cursor: 'pointer',
      }}>
      <ProButton className="flex-1" type="primary" onClick={handleOutCreateMode}>
        完成新建
      </ProButton>
    </div>
  ) : null;
}
export default BatchModelTool;
