import { useNodes } from "@xyflow/react";
import { AppNode, nodeLabel } from "@/lib/state";
import { NodeDetails } from "@/components/node-details";
import { Accordion, AccordionContent, AccordionTrigger } from "./ui/accordion";
import { AccordionItem } from "@radix-ui/react-accordion";
import { useMemo, useState } from "react";
import { Icon } from "./icon";

function unique<T>(v: T, i: number, a: T[]) {
  return a.indexOf(v) === i;
}

export function Details() {
  const nodes = useNodes<AppNode>();
  const [open, setOpen] = useState<string[]>([]);
  const selected = useMemo(() => nodes.filter((n) => n.selected).map((n) => n.id), [nodes]);
  const all = useMemo(() => open.concat(selected).filter(unique), [open, selected]);
  return (
    <Accordion type="multiple" value={all} onValueChange={(v) => setOpen(v)}>
      {nodes.filter((n) => n.type !== "network").map((n) => (
        <AccordionItem key={n.id} value={n.id} className="px-3">
          <AccordionTrigger>
            <div className="flex flex-row space-x-2">
              {Icon(n.type)}
              <span>{nodeLabel(n)}</span>
            </div>
          </AccordionTrigger>
          <AccordionContent>
            <NodeDetails {...n} />
          </AccordionContent>
        </AccordionItem>
      ))}
    </Accordion>
  );
}
