import cx from 'clsx';
import {Text} from '@mantine/core';
import {useListState} from '@mantine/hooks';
import {DragDropContext, Droppable, Draggable} from '@hello-pangea/dnd';
import classes from './DndList.module.css';


const data = [
    {position: 6, mass: 12.011, symbol: 'C', name: 'Carbon'},
    {position: 7, mass: 14.007, symbol: 'N', name: 'Nitrogen'},
    {position: 39, mass: 88.906, symbol: 'Y', name: 'Yttrium'},
    {position: 56, mass: 137.33, symbol: 'Ba', name: 'Barium'},
    {position: 58, mass: 140.12, symbol: 'Ce', name: 'Cerium'},
];

export function DndList() {
    const [state, handlers] = useListState(data);

    const items = (listIndex: number) => state.map((item, index) => (
        <Draggable key={item.symbol + `${listIndex}`} index={index} draggableId={item.symbol + `${listIndex}`}>
            {(provided, snapshot) => (
                <div
                    className={cx(classes.item, {[classes.itemDragging]: snapshot.isDragging})}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    ref={provided.innerRef}
                >
                    <Text className={classes.symbol}>{item.symbol}</Text>
                    <div>
                        <Text>{item.name}</Text>
                        <Text c="dimmed" size="sm">
                            Position: {item.position} • Mass: {item.mass}
                        </Text>
                    </div>
                </div>
            )}
        </Draggable>
    ));

    return (
        <DragDropContext
            onDragEnd={({destination, source}) =>
                handlers.reorder({from: source.index, to: destination?.index || 0})
            }
        >
            <Droppable droppableId="dnd-list" direction="vertical">
                {(provided) => (
                    <div {...provided.droppableProps} ref={provided.innerRef}>
                        {items(1)}
                        {provided.placeholder}
                    </div>
                )}
            </Droppable>
            <Droppable droppableId="dnd-list-2" direction="vertical">
                {(provided) => (
                    <div {...provided.droppableProps} ref={provided.innerRef}>
                        {items(2)}
                        {provided.placeholder}
                    </div>
                )}
            </Droppable>
        </DragDropContext>
    );
}