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

const CategoryRowFragment = graphql(`
  fragment CategoryRow on ProductCategory {
    id
    name
    code
    parent {
      id
      name
    }
  }
`);

export const CategoriesTableFragment = graphql(
  `
    fragment CategoriesTable on ProductCategoryConnection {
      edges {
        node {
          ...CategoryRow
        }
      }
    }
  `,
  [CategoryRowFragment],
);

interface CategoryRowProps {
  category: FragmentOf<typeof CategoryRowFragment>;
}

const CategoryRow = ({ category: categoryFragment }: CategoryRowProps) => {
  const category = readFragment(CategoryRowFragment, categoryFragment);

  return (
    <Table.Row>
      <Table.Cell>{category.name}</Table.Cell>
      <Table.Cell>{category.code}</Table.Cell>
      <Table.Cell>{category.parent?.name ?? "—"}</Table.Cell>
      <Table.Cell>
        <Button variant="ghost" size="sm" render={<Link to={category.id} />}>
          View
        </Button>
      </Table.Cell>
    </Table.Row>
  );
};

interface CategoriesTableProps {
  data: FragmentOf<typeof CategoriesTableFragment>;
}

export const CategoriesTable = ({ data }: CategoriesTableProps) => {
  const connection = readFragment(CategoriesTableFragment, data);

  return (
    <Table.Root>
      <Table.Header>
        <Table.Row>
          <Table.Head>Name</Table.Head>
          <Table.Head>Code</Table.Head>
          <Table.Head>Parent</Table.Head>
          <Table.Head />
        </Table.Row>
      </Table.Header>
      <Table.Body>
        {connection.edges.length === 0 ? (
          <Table.Row>
            <Table.Cell colSpan={4}>
              <EmptyState
                title="No categories"
                message="Get started by creating a new category."
                action={<Button render={<Link to="create" />}>Create Category</Button>}
              />
            </Table.Cell>
          </Table.Row>
        ) : (
          connection.edges.map((edge) => {
            const { id } = readFragment(CategoryRowFragment, edge.node);
            return <CategoryRow key={id} category={edge.node} />;
          })
        )}
      </Table.Body>
    </Table.Root>
  );
};
