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

import { eventContextMenu } from "shared/lib/slickgrid";
import { showNotification } from "shared/ui/notification";

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

export const CopyToClipboard: FC<IProps> = ({ setIsOpened }) => {
	function onClick() {
		const table = eventContextMenu.table;
		const grid = table?.grid;
		if (!grid || !table) {
			setIsOpened(false);
			return;
		}

		window.navigator.clipboard
			.writeText(table.downloadManager.createCSV(table))
			.then((): void => {
				showNotification("Copied to clipboard", "info");
			})
			.catch((): void => {
				showNotification("Failed to copy to clipboard", "warning");
			});

		if (grid.getSelectionModel()) {
			grid.setSelectedRows([]);
		}
		setIsOpened(false);
	}

	return (
		<Styled.Li onClick={onClick}>
			<Styled.Icon className={"sgi sgi-content-copy"}></Styled.Icon>Copy to
			clipboard
		</Styled.Li>
	);
};

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