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

const ProductRowFragment = graphql(`
  fragment ProductRow on Product {
    id
    name
    code
    status
    unit {
      name
      symbol
    }
  }
`);

export const ProductsTableFragment = graphql(
  `
    fragment ProductsTable on ProductConnection {
      edges {
        node {
          ...ProductRow
        }
      }
    }
  `,
  [ProductRowFragment],
);

interface ProductRowProps {
  product: FragmentOf<typeof ProductRowFragment>;
}

const ProductRow = ({ product: productFragment }: ProductRowProps) => {
  const product = readFragment(ProductRowFragment, productFragment);

  return (
    <Table.Row>
      <Table.Cell>{product.name}</Table.Cell>
      <Table.Cell>{product.code}</Table.Cell>
      <Table.Cell>
        {product.unit ? `${product.unit.name} (${product.unit.symbol})` : "—"}
      </Table.Cell>
      <Table.Cell>
        <Badge
          variant={
            product.status === "ACTIVE"
              ? "success"
              : product.status === "DRAFT"
                ? "info"
                : "neutral"
          }
        >
          {product.status}
        </Badge>
      </Table.Cell>
      <Table.Cell>
        <Button variant="ghost" size="sm" render={<Link to={product.id} />}>
          View
        </Button>
      </Table.Cell>
    </Table.Row>
  );
};

interface ProductsTableProps {
  data: FragmentOf<typeof ProductsTableFragment>;
}

export const ProductsTable = ({ data }: ProductsTableProps) => {
  const connection = readFragment(ProductsTableFragment, data);

  return (
    <Table.Root>
      <Table.Header>
        <Table.Row>
          <Table.Head>Name</Table.Head>
          <Table.Head>Code</Table.Head>
          <Table.Head>Unit</Table.Head>
          <Table.Head>Status</Table.Head>
          <Table.Head />
        </Table.Row>
      </Table.Header>
      <Table.Body>
        {connection.edges.length === 0 ? (
          <Table.Row>
            <Table.Cell colSpan={5}>
              <EmptyState
                title="No products"
                message="Get started by creating a new product."
                action={<Button render={<Link to="create" />}>Create Product</Button>}
              />
            </Table.Cell>
          </Table.Row>
        ) : (
          connection.edges.map((edge) => {
            const { id } = readFragment(ProductRowFragment, edge.node);
            return <ProductRow key={id} product={edge.node} />;
          })
        )}
      </Table.Body>
    </Table.Root>
  );
};
