import React, { memo } from 'react';
import classNames from 'classnames';
import LayerControl from './LayerControl';
import EditableText from './EditableText';
import styles from './LayerGroup.less';

export default memo(function LayerGroup({
  id,
  show,
  collapsed,
  lock,
  name,
  selected,
  level,
  draggableId,
  onSelect,
  onChange
}: {
  id: string | number;
  show: boolean;
  collapsed: boolean;
  lock: boolean;
  name: string;
  selected: boolean;
  level: number;
  draggableId: number | string;
  onSelect: (e, id) => any;
  onChange: (param) => any;
}) {
  const handleCollapse = (e) => {
    e.stopPropagation();
    onChange([{ id, key: 'collapsed', value: !collapsed }]);
  };

  const handleClick = (e) => {
    e.stopPropagation();
    onSelect(e, id);
  };

  const onComponentUnlock = (e) => {
    e.stopPropagation();
    onChange([{ id, key: 'lock', value: false }]);
  };

  const handleMouseEnter = () => {
    const dom = document.getElementById(`${id}`);
    if (dom) {
      dom.classList.add('z-hover');
    }
  };

  const handleMouseLeave = () => {
    const dom = document.getElementById(`${id}`);
    if (dom) {
      dom.classList.remove('z-hover');
    }
  };

  return (
    <div
      id={`layer_${id}`}
      className={classNames(styles.groupName, {
        [styles.selected]: selected,
        [styles.nodragging]: draggableId && draggableId !== id,
        collapsed: collapsed
      })}
      onClick={handleClick}
      style={{ paddingLeft: 12 + level * 16 }}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}>
      <LayerControl id={id} show={show} selected={selected} onShow={onChange} />
      <span
        className={classNames(styles.collapseIcon, {
          [styles.collapsed]: collapsed
        })}
        onClick={handleCollapse}>
        <i className="icon iconfont icon-btn_fold1" />
      </span>
      <span className={styles.folderIcon}>
        <i className="icon iconfont icon-zu" />
      </span>
      <EditableText id={id} text={name} selected={selected} updateName={onChange} />
      {lock && <i className="icon iconfont icon-icon_lock" style={{ cursor: 'pointer', fontSize: 14 }} onClick={onComponentUnlock} />}
    </div>
  );
});
