import React from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import classNames from 'classnames';
import { SortableElement } from 'react-sortable-hoc';
import EditableText from './EditableText';
import styles from './SortableItem.less';

export default SortableElement(function SortableItem({ value, active, onContextMenu, updateName }) {
  const history = useHistory();
  const location = useLocation();
  const handleClick = () => {
    if (!active) {
      const pathname = location.pathname;
      const pathnameArr = pathname.split('/');
      pathnameArr[pathnameArr.length - 1] = value.id;
      history.replace(pathnameArr.join('/'));
    }
  };

  const handleContextMenu = (e) => {
    e.preventDefault();
    onContextMenu(value.id, { x: e.clientX, y: e.clientY });
  };

  return (
    <li className={classNames(styles.container, { [styles.active]: active })} onClick={handleClick} onContextMenu={handleContextMenu}>
      <i className="icon iconfont icon-File" style={{ fontSize: 12, marginRight: 4 }} />
      <EditableText id={value.id} text={value.name} selected={active} updateName={updateName} />
    </li>
  );
});
