import { Button } from "@/components/ui/button";
import { v4 as uuidv4 } from "uuid";
import { useCallback, useState } from "react";
import { Accordion, AccordionTrigger } from "./ui/accordion";
import { AccordionContent, AccordionItem } from "@radix-ui/react-accordion";
import { AppNode, AppState, NodeType, useCategories, useStateStore } from "@/lib/state";
import { CategoryItem } from "@/lib/categories";
import { Icon } from "./icon";

function addResource(i: CategoryItem<NodeType>, store: AppState) {
	const node = {
		id: uuidv4(),
		position: {
			x: 0,
			y: 0,
		},
		type: i.type,
		connectable: true,
		data: i.init,
		selected: true,
	};
	const nodes = store.nodes.map((n) => ({
		...n,
		selected: false,
	}));
	nodes.push(node as AppNode);
	store.setNodes(nodes);
}

export function Resources() {
	const store = useStateStore();
	const categories = useCategories();
	const onResourceAdd = useCallback(
		(item: CategoryItem<NodeType>) => {
			return () => addResource(item, store);
		},
		[store],
	);
	const [open, setOpen] = useState<string[]>(categories.map((c) => c.title));
	return (
		<>
			<Accordion type="multiple" value={open} onValueChange={(v) => setOpen(v)}>
				{categories.map((c) => (
					<AccordionItem key={c.title} value={c.title} className={"px-3" + (c.active ? " bg-amber-100" : "")}>
						<AccordionTrigger>{c.title}</AccordionTrigger>
						<AccordionContent>
							<div className="flex flex-col space-y-1">
								{c.items.map((item: CategoryItem<NodeType>) => (
									<Button
										key={item.title}
										onClick={onResourceAdd(item)}
										style={{ justifyContent: "flex-start" }}
									>
										<Icon type={item.type} />
										{item.title}
									</Button>
								))}
							</div>
						</AccordionContent>
					</AccordionItem>
				))}
			</Accordion>
		</>
	);
}
