import React, { useRef, useState, useEffect } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import classnames from 'classnames';
import styles from './index.less';

const DraggableBodyRow = ({
  name,
  index,
  moveRow,
  className,
  style,
  tableType,
  ItemTypes,
  ...restProps
}) => {
  const [type, setType] = useState('');
  const ref = useRef();
  useEffect(() => {
    if (ItemTypes) {
      setType(ItemTypes);
    }
  }, [ItemTypes]);
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: monitor => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
        dropClassName: dragIndex < index ? 'drop-over-downward' : 'drop-over-upward',
      };
    },
    drop: item => {
      moveRow(item.index, index, tableType);
    },
  });
  const [, drag] = useDrag({
    type,
    item: { index },
    collect: monitor => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));
  return (
    <tr
      ref={ref}
      className={classnames({
        [className]: true,
        [styles[dropClassName]]: isOver,
      })}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};

export default DraggableBodyRow;