import React, { Component } from 'react';
import { DragSource, DropTarget } from 'react-dnd';
import Thumb from 'components/Thumb';
import styles from '../SortItem.less';
import {getAssetsUrl} from 'utils/utils';

const cardSource = {
  beginDrag(props) {
    return {
      id: props.id,
      index: props.index
    };
  }
};

function sourceCollect(connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging()
  };
}

const cardTarget = {
  hover(props, monitor, component) {
    if (!component) {
      return null;
    }
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;

    if (dragIndex === hoverIndex) {
      return;
    }

    props.moveCard(dragIndex, hoverIndex);
    monitor.getItem().index = hoverIndex;
  }
};

function targetCollect(connect) {
  return {
    connectDropTarget: connect.dropTarget()
  };
}

interface IProps {
  id: string;
  index: number;
  className: string;
  data: any;
  isDragging: boolean;
  connectDragSource: any;
  connectDropTarget: any;
  moveCard: (dragIndex: any, hoverIndex: any) => void;
}

class Card extends Component<IProps> {
  render() {
    const { data, isDragging, connectDragSource, connectDropTarget } = this.props;
    const opacity = isDragging ? 0 : 1;

    return connectDragSource(
      connectDropTarget(
        <div className={styles.item} style={{ opacity }}>
          <Thumb src={data.thumb ? getAssetsUrl(`${data.thumb}`) : undefined} />
          <span className={styles.name}>{data.name}</span>
        </div>
      )
    );
  }
}

export default DropTarget('card', cardTarget, targetCollect)(DragSource('card', cardSource, sourceCollect)(Card));
