import { Badge, Button, Link, Table } from "@tailor-platform/app-shell";
import { EmptyState } from "@/components/composed/empty-state";
import { graphql, type FragmentOf, readFragment } from "@/graphql";

const RoleRowFragment = graphql(`
  fragment RoleRow on Role {
    id
    name
    description
    status
    permissions
  }
`);

export const RolesTableFragment = graphql(
  `
    fragment RolesTable on RoleConnection {
      edges {
        node {
          ...RoleRow
        }
      }
    }
  `,
  [RoleRowFragment],
);

interface RoleRowProps {
  role: FragmentOf<typeof RoleRowFragment>;
}

const RoleRow = ({ role: roleFragment }: RoleRowProps) => {
  const role = readFragment(RoleRowFragment, roleFragment);
  const permissions = [...(role.permissions ?? [])].sort();

  return (
    <Table.Row>
      <Table.Cell>{role.name}</Table.Cell>
      <Table.Cell>{role.description ?? "-"}</Table.Cell>
      <Table.Cell>
        <Badge variant={role.status === "ACTIVE" ? "success" : "neutral"}>{role.status}</Badge>
      </Table.Cell>
      <Table.Cell>
        {permissions.length > 0 ? (
          <Badge variant="outline-neutral">{permissions.length} scopes</Badge>
        ) : (
          <span className="text-muted-foreground">-</span>
        )}
      </Table.Cell>
      <Table.Cell>
        <Button variant="ghost" size="sm" render={<Link to={role.id} />}>
          View
        </Button>
      </Table.Cell>
    </Table.Row>
  );
};

interface RolesTableProps {
  data: FragmentOf<typeof RolesTableFragment>;
}

export const RolesTable = ({ data }: RolesTableProps) => {
  const connection = readFragment(RolesTableFragment, data);

  return (
    <Table.Root>
      <Table.Header>
        <Table.Row>
          <Table.Head>Name</Table.Head>
          <Table.Head>Description</Table.Head>
          <Table.Head>Status</Table.Head>
          <Table.Head>Permissions</Table.Head>
          <Table.Head />
        </Table.Row>
      </Table.Header>
      <Table.Body>
        {connection.edges.length === 0 ? (
          <Table.Row>
            <Table.Cell colSpan={5}>
              <EmptyState
                title="No roles"
                message="Get started by creating a new role."
                action={<Button render={<Link to="create" />}>Create Role</Button>}
              />
            </Table.Cell>
          </Table.Row>
        ) : (
          connection.edges.map((edge) => {
            const { id } = readFragment(RoleRowFragment, edge.node);
            return <RoleRow key={id} role={edge.node} />;
          })
        )}
      </Table.Body>
    </Table.Root>
  );
};
