import { Badge, DescriptionCard } from "@tailor-platform/app-shell";
import { graphql, type FragmentOf, readFragment } from "@/graphql";
import { groupPermissions, isAutoAssigned } from "@/lib/permission-groups";

export const RoleDetailFragment = graphql(`
  fragment RoleDetail on Role {
    id
    name
    description
    createdAt
    rolePermissions {
      edges {
        node {
          id
          permission {
            id
            key
            description
          }
        }
      }
    }
  }
`);

interface RoleDetailProps {
  role: FragmentOf<typeof RoleDetailFragment>;
}

export const RoleDetail = ({ role: roleFragment }: RoleDetailProps) => {
  const role = readFragment(RoleDetailFragment, roleFragment);
  const assignedPermissions = role.rolePermissions.edges
    .map((edge) => edge.node.permission)
    .filter((p): p is NonNullable<typeof p> => p != null)
    .filter((p) => !isAutoAssigned(p));
  const assignedGroups = groupPermissions(assignedPermissions);

  return (
    <div className="space-y-6">
      <DescriptionCard
        data={role}
        title="Role Information"
        columns={3}
        fields={[
          { key: "name", label: "Name" },
          { key: "description", label: "Description" },
          {
            key: "createdAt",
            label: "Created At",
            type: "date",
            meta: { dateFormat: "medium" },
          },
        ]}
      />
      <div className="rounded-lg border p-4">
        <h3 className="mb-3 text-sm font-medium">Permissions</h3>
        {assignedGroups.length === 0 ? (
          <p className="text-sm text-muted-foreground">No permissions assigned.</p>
        ) : (
          <div className="flex flex-wrap gap-2">
            {assignedGroups.map((group) => (
              <Badge key={group.label}>{group.label}</Badge>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};
