import React, { useState, useRef, memo } from 'react';
import classNames from 'classnames';
import EditableText from 'components/EditableText';
import DragTargetContainer from './DragTargetContainer';
import styles from './GroupMenu.less';
import message from 'components/message';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';

function GroupItem({ id, index, active, name, groupedCount, isFirst, moveScreenToGroup, selectGroup, deleteGroup, updateGroup }) {
  const [focus, setFocus] = useState(false);
  const editRef = useRef(null);
  const deleteRef = useConfirmRef();

  const handleDrop = () => {
    moveScreenToGroup({
      groupId: id
    });
  };

  const handleNameChange = (value) => {
    if (value.length > 50) {
      message.error('分组名不能超过50个字符');
      return;
    }
    updateGroup({
      groupId: id,
      name: value
    });
  };

  const handleDelete = () => {
    deleteGroup(id);
  };

  const handleFocus = () => {
    setFocus(true);
  };

  const handleBlur = () => {
    setFocus(false);
  };

  return (
    <DragTargetContainer active={active} onDrop={handleDrop} index={index} id={id}>
      <div
        className={classNames(styles.menuItem, { [styles.active]: active, [styles.isFirst]: isFirst })}
        id={id}
        onClick={() => selectGroup(id)}>
        <div className={styles.nameContainer}>
          <EditableText
            ref={editRef}
            text={name}
            className={styles.editName}
            doubleClick={true}
            placeholder="输入组名"
            onCommit={handleNameChange}
            onFocus={handleFocus}
            onBlur={handleBlur}
          />
        </div>
        <div className={styles.rightIcon}>
          <span>
            <span className={classNames(styles.groupedCount)}>{focus ? '' : `${groupedCount}`}</span>
            <i
              className={classNames('icon', 'iconfont', 'icon-custom', styles.editIcon)}
              onClick={(e) => {
                editRef.current?.onEdit(e);
              }}
            />
          </span>
          <i onClick={() => deleteRef.current?.show()} className={classNames('icon', 'iconfont', 'icon-btn_delete', styles.deleteIcon)} />
          <EasyvModal.Confirm
            content={
              <span style={{ color: 'rgb(171,174,185)' }}>
                <span style={{ color: '#fff' }}>{name}</span>分组删除后，分组下的大屏将被移入未分组当中，确认删除？
              </span>
            }
            title="删除分组"
            onOk={handleDelete}
            ref={deleteRef}
          />
        </div>
      </div>
    </DragTargetContainer>
  );
}

export default memo(GroupItem);
