import React, { useState, useCallback, useEffect, useRef, useMemo } from 'react';
import { useSelector } from 'react-redux';
import classNames from 'classnames';
import UpgradeList from './UpgradeList';
import styles from '../index.less';
import { getTopScreenId, getScreenComponents, isMobileScreen } from 'utils/screen';
import { isLowVersion } from 'utils/utils';

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

  const screenId = getTopScreenId();
  const { componentsById, panelsById, screensById } = useSelector<any, any>(({ componentsById, panelsById, screensById }) => ({
    componentsById,
    panelsById,
    screensById
  }));
  const constants = useSelector<any, any>(({ mobileConstants, constants }) => (isMobileScreen() ? mobileConstants.list : constants.list));
  const components = useMemo(() => getScreenComponents(screenId, { screensById, componentsById, panelsById }), [
    screenId,
    componentsById,
    panelsById,
    screensById
  ]);

  const enableUpgradedComponents = useMemo(
    () =>
      components.filter((d) => {
        const constant = constants.find((o) => o.moduleName === d.base.module_name);
        return constant && isLowVersion(d.base.version, constant.version);
      }),
    [components, constants]
  );

  return (
    <div className={styles.item} ref={containerRef}>
      <span
        onClick={() => setVisible(true)}
        className={classNames({ [styles.info]: enableUpgradedComponents.length > 0, [styles.active]: visible })}>
        {children}
      </span>
      <UpgradeList visible={visible} onClose={handleClose} data={enableUpgradedComponents} />
    </div>
  );
}

export default ComponentsUpgrade;
