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

function FilterContainer({ 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, false);
    };
  }, []);

  const handleContainerClick = (e) => {
    e.stopPropagation();
  };

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

      <Filter visible={visible} onClose={handleClose} />
    </div>
  );
}

export default FilterContainer;
