// 2d分子结构图
import { useEffect } from "react";
import { Box } from "@mui/material";
import { useMessage } from "@/components/MySnackbar";
var Kekule = require("kekule").Kekule;

type IKekuleViewProps = {
	id: string;
	width?: string;
	height?: string;
	smi: string;
	backgroundColor?: string;
	style?: any;
	onClick?: any;
	toolbar?: boolean;
};

declare global {
	interface Window {
		RDKit: any;
	}
}

const KekuleView = (props: IKekuleViewProps) => {
	const {
		id,
		width = "100%",
		height = "100%",
		smi = "",
		backgroundColor = "#fff",
		style = {},
		onClick,
		toolbar = false,
	} = props;
	const Message = useMessage();

	useEffect(() => {
		if (smi) {
			try {
				let molecule = Kekule.IO.loadFormatData(
					window.RDKit.get_mol(smi).get_kekule_form(),
					"mol"
				);
				const contentBox = document.getElementById(id);
				if (contentBox) {
					contentBox.innerHTML = "";
				}
				let chemViewer = new Kekule.ChemWidget.Viewer(document);
				chemViewer.setDimension(width, height);
				chemViewer.setBackgroundColor(backgroundColor);
				chemViewer
					.appendToElem(document.getElementById(id))
					.setChemObj(molecule);
				chemViewer.setEnableToolbar(toolbar);
				chemViewer.setAutofit(true);
				chemViewer.setPadding(16);
				chemViewer.setEnableDirectInteraction(false);
			} catch (err) {
				console.log(err);
				Message.error("分子结构图渲染失败，请刷新重试。");
			}
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [smi]);

	return (
		<Box
			id={id}
			sx={{
				cursor: onClick ? "pointer" : "unset",
				width: "100%",
				height: "100%",
				...style,
			}}
			onClick={onClick}
		></Box>
	);
};

export default KekuleView;
