import React, { memo } from 'react';
import { useDrag } from 'react-dnd';
import Thumb from 'components/Thumb';
import styles from './GalleryGroupItem.less';
import { getAssetsUrl } from 'utils/utils';

function GalleryGroupItem({ base, addComponent }) {
  const { name, moduleName, version, thumb } = base;

  const [, drag] = useDrag({
    item: { name, type: 'component' },
    end: (item, monitor) => {
      const dropResult = monitor.getDropResult();
      if (item && dropResult) {
        addComponent({ name, moduleName, version, position: { x: dropResult.position.x + 50, y: dropResult.position.y + 30 } });
      }
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging
    })
  });

  const handleClick = () => {
    addComponent({ name, moduleName, version });
  };

  const handleDrag = (e) => {
    e.dataTransfer.effectAllowed = 'move';
  };

  return (
    <li ref={drag} className={styles.cpnt} onClick={handleClick} onDragStart={handleDrag}>
      <Thumb className={styles.img} src={thumb ? getAssetsUrl(`${thumb}`) : undefined} />
      <p className={styles.name}>{name}</p>
    </li>
  );
}

export default memo(GalleryGroupItem);
