import React, { useRef, FC } from 'react';
import classNames from 'classnames';
import { useDrag, useDrop } from 'react-dnd';

const Card : FC<{ active: boolean; id?: number; index?: number; disableDrag?: boolean; onDrop: Function}> = ({ active, children, id, index, disableDrag, onDrop }) => {
  const ref = useRef(null);
  const [{ isOver, itemType }, drop] = useDrop({
    accept: disableDrag ? ['box'] : ['box', 'GroupItem'],
    drop(item) {
      // 屏幕拖动到分组
      if ('box' === item.type) {
        if (!active) {
          onDrop && onDrop();
        }
      }
    },
    collect(monitor) {
      return {
        isOver: monitor.isOver(),
        itemType: monitor.getItemType()
      };
    }
  });
  const [{ isDragging }, drag] = useDrag({
    item: { type: 'GroupItem', id, index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  });
  const opacity = isDragging ? 0 : 1;
  // hover效果只有屏幕拖到组上才有
  const _isOver = itemType === 'box' ? isOver : false;
  if (disableDrag) {
    drop(ref);
  } else {
    drag(drop(ref));
  }
  return (
    <div ref={ref} style={{ opacity }} className={classNames({ isOver: _isOver })}>
      {children}
    </div>
  );
}

export default Card
