import DraggableList from 'react-draggable-list';
import { DataRow } from '../api/DataRow';
import { Post } from './display/Post';

import style from './DraggablePostsList.module.scss';
import { GripVertical } from './display/GripVertical';

type SetRowsFunction = (data: DataRow[]) => void;

function PostDraggableListItem({ item, dragHandleProps, rows, setRows }: { item: DataRow, dragHandleProps: object, setRows: SetRowsFunction, rows: DataRow[] }) {

    function onChange() {
        rows.splice(rows.indexOf(item), 1);
        setRows([ ...rows ]);
    }

    return (
        <div className={style.draggableListRow}>
            <span>
                <label for={`row-list-${item.id}`} style={{ display: 'none' }}>Select</label>
                <input type='checkbox' id={`row-list-${item.id}`} checked onChange={onChange}/>
                <GripVertical {...dragHandleProps} />
            </span>
            <Post className={style.posts} row={item} />
        </div>
    )
}

export type DraggablePostsList = {
    rows: DataRow[],
    setRows: SetRowsFunction
};
export function DraggablePostsList(props: DraggablePostsList) {
    return (
        <DraggableList
            itemKey={'id'}
            // @ts-expect-error
            template={p => PostDraggableListItem({ ...p, setRows: props.setRows, rows: props.rows })}
            list={props.rows}
            onMoveEnd={rows => props.setRows([ ...rows ])}
        />
    );
}