import { React, ReactDND, PropTypes } from '@gravityforms/libraries';
import KanbanCard from './KanbanCard';
import KanbanColumn from './KanbanColumn';
import itemTypes from './item-types';

const { useDragLayer } = ReactDND;

const getItemStyles = ( initialOffset, currentOffset, rect ) => {
	if ( ! initialOffset || ! currentOffset ) {
		return {
			display: 'none',
		};
	}

	const dragHandleWidth = 35;
	const padding = 12;
	const border = 1;
	const { x, y } = currentOffset;
	const { width: columnWidth, height: columnHeight } = rect;
	const width = columnWidth + ( padding * 2 ) + ( border * 2 );
	const height = columnHeight + ( padding * 2 ) + ( border * 2 );
	const transform = `translate(calc(${ x + padding + border + dragHandleWidth }px - 100%), ${ y - padding - border }px)`;

	return { height, width, transform };
};

const KanbanDragLayer = ( {
	i18n = {},
	kanbanId = '',
} ) => {
	const { itemType, isDragging, item, initialOffset, currentOffset } = useDragLayer( ( monitor ) => ( {
		item: monitor.getItem(),
		itemType: monitor.getItemType(),
		initialOffset: monitor.getInitialSourceClientOffset(),
		currentOffset: monitor.getSourceClientOffset(),
		isDragging: monitor.isDragging(),
	} ) );

	const columnItemType = `${ itemTypes.KANBAN_COLUMN }_${ kanbanId }`;

	if ( ! isDragging || itemType !== columnItemType ) {
		return null;
	}

	const { column, index, rect } = item;

	const columnId = `${ kanbanId }-${ column.id }-drag-layer`;
	const columnProps = {
		...column.props,
		i18n,
		id: columnId,
		index,
		isDragLayer: true,
		kanbanId,
	};

	return (
		<div className="gform-kanban__drag-layer">
			<div style={ getItemStyles( initialOffset, currentOffset, rect ) }>
				<KanbanColumn { ...columnProps }>
					{ column.cards.map( ( card, cardIndex ) => {
						const CardComponent = card.component || KanbanCard;
						const cardProps = {
							...card.props,
							columnId,
							i18n,
							index: cardIndex,
							kanbanId,
						};

						return <CardComponent { ...cardProps } key={ `${ card.props.id }-drag-layer` } />;
					} ) }
				</KanbanColumn>
			</div>
		</div>
	);
};

KanbanDragLayer.propTypes = {
	i18n: PropTypes.object,
	kanbanId: PropTypes.string,
};

export default KanbanDragLayer;
