import React, { useState, memo, useEffect, useCallback } from 'react';
import PropTypes from 'prop-types';
import Mousetrap from 'mousetrap';
import ViewControl from './ViewControl';
import ShortcutsPanel from './ShortcutsPanel';
import Setting from './Setting';
import Help from './Help';
import styles from './index.less';
import { isNodePage } from 'utils/utils';

function ToolBar({ leftShow, rightShow }) {
  const [viewVisible, setView] = useState(false);
  const [shortcutsVisible, setShortcuts] = useState(false);
  const [settingVisible, setSettingVisible] = useState(false);
  const [helpVisible, setHelpVisible] = useState(false);
  const isNodesPage = isNodePage();

  const onHide = () => {
    if (viewVisible) {
      setView(false);
    }
    if (helpVisible) {
      setHelpVisible(false);
    }
    if (shortcutsVisible) {
      setShortcuts(false);
    }
    if (settingVisible) {
      setSettingVisible(false);
    }
  };

  useEffect(() => {
    document.addEventListener('click', onHide, false);
    return () => {
      document.removeEventListener('click', onHide);
    };
  }, [viewVisible, helpVisible, settingVisible]);

  const onZoomIn = useCallback(() => {
    Mousetrap.trigger('command+=');
  }, []);

  const onZoomOut = useCallback(() => {
    Mousetrap.trigger('command+-');
  }, []);

  const onZoomFit = useCallback(() => {
    Mousetrap.trigger('command+2');
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.left}>
        <span className={styles.item} onClick={() => setView(!viewVisible)}>
          视图调整
        </span>
        <span className={styles.item} onClick={() => setHelpVisible(!helpVisible)}>
          帮助
        </span>
        {!isNodesPage && (
          <span className={styles.item} onClick={() => setSettingVisible(!settingVisible)}>
            设置
          </span>
        )}
      </div>
      <div className={styles.right}>
        <span className={styles.item} onClick={onZoomOut}>
          <i className="icon iconfont icon-btn_zoom_out" />
        </span>
        <span className={styles.item} onClick={onZoomIn}>
          <i className="icon iconfont icon-btn_zoom_in" />
        </span>
        <span className={styles.item} onClick={onZoomFit}>
          <i className="icon iconfont icon-btn_fullscreen" />
        </span>
      </div>

      {viewVisible && <ViewControl leftShow={leftShow} rightShow={rightShow} />}
      {shortcutsVisible && <ShortcutsPanel onClose={() => setShortcuts(false)} />}
      {helpVisible && <Help onShortcuts={() => setShortcuts(true)} />}
      {settingVisible && <Setting />}
    </div>
  );
}

ToolBar.propTypes = {
  leftShow: PropTypes.bool,
  rightShow: PropTypes.bool,
  onLeftToggle: PropTypes.func,
  onRightToggle: PropTypes.func
};

export default memo(ToolBar);
