import React, { useState, useCallback, useEffect, useRef } from 'react';
import classNames from 'classnames';
import Relationship from './Relationship';
import styles from '../index.less';

function CallbackContainer({ children, onRecycleCallback, isClose }) {
  const [visible, setVisible] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  const handleClose = useCallback(() => {
    setVisible(false);
  }, []);

  useEffect(() => {
    !isClose && setVisible(false);
  }, [isClose]);

  useEffect(() => {
    onRecycleCallback?.(visible);
  }, [visible]);

  useEffect(() => {
    const handleClick = (e) => {
      if (!containerRef.current?.contains(e.target)) {
        const appDOM = document.getElementById('easyv-app');
        if (appDOM && appDOM.contains(e.target)) {
          setVisible(false);
        }
      }
    };

    document.addEventListener('click', handleClick, false);

    return () => {
      document.removeEventListener('click', handleClick);
    };
  }, []);

  return (
    <div className={styles.item} ref={containerRef}>
      <span onClick={() => setVisible(true)} className={classNames({ [styles.active]: visible })}>
        {children}
      </span>

      <Relationship visible={visible} onClose={handleClose} searchText="" />
    </div>
  );
}

export default CallbackContainer;
