import React, { useCallback, useState } from 'react';
import classNames from 'classnames';
import EditableText from './EditableText';
import LayerIcon from './LayerIcon';
import styles from './SortableListGroup.less';
import { getLayerHoverStatus } from '../../../../utils/effects';
import { PartialStateShare } from '../../../../utils/utils';

export default function SortableListGroup({
  id,
  name,
  show,
  collapsed,
  selected,
  lock,
  focus,
  level,
  onSelect,
  onUpdate,
  onContextMenu,
  updateName
}) {
  const isHover = getLayerHoverStatus(id);
  const [showEye, setEye] = useState(false);
  const handleClick = (e) => {
    onSelect(e, id);
  };

  const handleContextMenu = (e) => {
    onContextMenu(e, id);
  };

  const handleMouseEnter = () => {
    PartialStateShare.emit('mouse_over_layer', { hover: id });
    setEye(true);
  };

  const handleMouseLeave = () => {
    PartialStateShare.emit('mouse_over_layer', null);
    setEye(false);
  };

  const handleIconClick = (type, value) => onUpdate(type, [id], value);

  const handleCollapsedChange = (e) => {
    e.stopPropagation();
    onUpdate('collapsed', [id], !collapsed);
  };

  const handleNameChange = useCallback(
    (value) => {
      updateName({ id, value });
    },
    [updateName, id]
  );

  const icons = [
    { type: 'focus', icon: 'delight', title: '单独显示图层', value: focus, show: focus },
    { type: 'show', icon: 'hide', title: show ? '隐藏' : '显示', value: show, show: showEye || !show },
    { type: 'lock', title: '锁定', value: lock, show: lock }
  ];

  return (
    <div
      id={`layer_${id}`}
      className={classNames(styles.container, { selected, hide: !show, 'z-hover': isHover })}
      style={{ paddingLeft: 12 + (level - 1) * 16 }}
      onClick={handleClick}
      onContextMenu={handleContextMenu}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}>
      <span className={classNames(styles.collapseIcon, { collapsed })} onClick={handleCollapsedChange}>
        <i className="icon iconfont icon-btn_fold1" />
      </span>
      <span className={styles.folderIcon}>
        <i className="icon iconfont icon-zu1" />
      </span>
      <EditableText id={id} text={name} selected={selected} updateName={handleNameChange} />
      {icons.map(({ title, type, icon, show, value }) => (
        <LayerIcon key={type} title={title} type={type} icon={icon} show={show} value={value} onChange={handleIconClick} />
      ))}
    </div>
  );
}
