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

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

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);
  return (
    <Table.Row>
      <Table.Cell>{role.name}</Table.Cell>
      <Table.Cell>{role.description ?? "-"}</Table.Cell>
      <Table.Cell>
        {/* eslint-disable-next-line react-x/purity -- parsing a fixed timestamp, not reading current time */}
        {role.createdAt ? new Date(role.createdAt).toLocaleDateString() : "-"}
      </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);

  if (connection.edges.length === 0) {
    return (
      <EmptyState
        title="No roles"
        message="Get started by creating a new role."
        action={<Button render={<Link to="create" />}>Create Role</Button>}
      />
    );
  }

  return (
    <Table.Root>
      <Table.Header>
        <Table.Row>
          <Table.Head>Name</Table.Head>
          <Table.Head>Description</Table.Head>
          <Table.Head>Created At</Table.Head>
          <Table.Head />
        </Table.Row>
      </Table.Header>
      <Table.Body>
        {connection.edges.map((edge) => {
          const { id } = readFragment(RoleRowFragment, edge.node);
          return <RoleRow key={id} role={edge.node} />;
        })}
      </Table.Body>
    </Table.Root>
  );
};
