import { Dispatch, FC, SetStateAction } from "react";
import { SlickDataView } from "slickgrid";

import {
	eventContextMenu,
	getNextId,
	positionToPaste,
} from "shared/lib/slickgrid";
import { IEditedRow, ISlickRow } from "shared/model/types";

import Styled from "../ContextMenu.style";

export const PasteRows: FC<IProps> = ({ setIsOpened }) => {
	const table = eventContextMenu.table;
	const copiedRows = table?.copiedRows || [];
	const grid = table?.grid;
	const options = grid?.getOptions();

	function pasteRows() {
		if (!grid || !table) {
			return;
		}
		const dataView: SlickDataView = grid.getData();
		const rows = dataView.getItems();
		const newRows: (ISlickRow & IEditedRow)[] = [];
		const idPropertyName = dataView.getIdPropertyName();
		let nextId = getNextId(grid);
		if (copiedRows.length) {
			copiedRows.forEach((row) => {
				newRows.push({
					...row,
					[idPropertyName]: nextId++,
					isEdited: true,
					isNew: true,
				});
			});
			rows.splice(positionToPaste(grid), 0, ...newRows);
			dataView.setItems(rows);
			grid.setSelectedRows([]);
			grid.invalidate();
			table.isEdited = true;
		}
		setIsOpened(false);
	}

	if (!options?.enableAddRow || !copiedRows.length) return null;

	return (
		<Styled.Li onClick={pasteRows}>
			<Styled.Icon className={"sgi sgi-content-paste"}></Styled.Icon>Paste rows
		</Styled.Li>
	);
};

interface IProps {
	setIsOpened: Dispatch<SetStateAction<boolean>>;
}
