import { groupPermissions } from "@/lib/groupPermission";
import { Anchor, Flex, Stack, Text } from "@mantine/core";
import { useState } from "react";

interface Node {
  label: string;
  children: any;
  actions: string[];
}

function RenderNode({ node }: { node: Node }) {
  const sub = Object.values(node.children || {});

  return (
    <Stack pl="md" gap={6}>
      {/* Title */}
      <Text size="sm">- {node.label}</Text>

      {/* Children */}
      {sub.map((child: any, i) => (
        <RenderNode key={i} node={child} />
      ))}
    </Stack>
  );
}

function RenderNode2({ node }: { node: Node }) {
  const sub = Object.values(node.children || {});

  return (
    <Flex direction={"row"} wrap={"wrap"} gap={6}>
      {/* Title */}
      <Text size="sm">{node.label},</Text>

      {/* Children */}
      {sub.map((child: any, i) => (
        <RenderNode2 key={i} node={child} />
      ))}
    </Flex>
  );
}

export default function PermissionRole({
  permissions,
}: {
  permissions: string[];
}) {
  const [showAll, setShowAll] = useState(false);
  if (!permissions?.length) return <Text c="dimmed">-</Text>;

  const groups = groupPermissions(permissions);
  const rootNodes = Object.values(groups);

  return (
    <Stack gap="sm">
      {showAll
        ? rootNodes.map((node: any, idx) => (
            <RenderNode key={idx} node={node} />
          ))
        : rootNodes
            .slice(0, 2)
            .map((node: any, idx) => <RenderNode2 key={idx} node={node} />)}
      <Anchor size="xs" onClick={() => setShowAll(!showAll)}>
        {showAll ? "View less" : "View more"}
      </Anchor>
    </Stack>
  );
}
