import { Box, Stack } from "@mui/material";
import { TreeItem2 } from "@mui/x-tree-view";
import { FC, ReactNode, useEffect, useState } from "react";

import { NodeMenuItem, NodeMenuView } from "./NodeMenuView";

export interface Node {
	id: string;
	modelId: string;
	name: string;
	menu?: NodeMenuItem[];
	state?: ReactNode;
	children?: Node[];
}

export const TreeNode: FC<{
	node: Node;
}> = ({ node }) => {
	const [menu, setMenu] = useState(node.menu);

	useEffect(() => {
		setMenu(node.menu);
	}, [node.menu]);

	return (
		<TreeItem2
			key={node.id}
			itemId={node.id}
			label={
				<Stack
					direction="row"
					justifyContent="space-between"
					sx={{
						width: "100%",
						height: "1.5rem",
					}}
					alignItems="center"
					title={node.name}
				>
					<Stack
						direction="row"
						sx={{
							width: "100%",
							overflow: "hidden",
						}}
						alignItems="center"
					>
						<Box
							component="span"
							sx={{
								whiteSpace: "nowrap",
								overflow: "hidden",
								textOverflow: "ellipsis",
							}}
							onClick={(event) => event.stopPropagation()}
						>
							{node.name}
						</Box>
					</Stack>

					{node.state && node.state}

					{menu && <NodeMenuView items={menu} />}
				</Stack>
			}
		>
			{node.children?.map((child) => (
				<TreeNode key={child.id} node={child} />
			))}
		</TreeItem2>
	);
};
