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

const AttributeRowFragment = graphql(`
  fragment AttributeRow on ProductAttribute {
    id
    name
    code
  }
`);

export const AttributesTableFragment = graphql(
  `
    fragment AttributesTable on ProductAttributeConnection {
      edges {
        node {
          ...AttributeRow
        }
      }
    }
  `,
  [AttributeRowFragment],
);

interface AttributeRowProps {
  attribute: FragmentOf<typeof AttributeRowFragment>;
}

const AttributeRow = ({ attribute: attributeFragment }: AttributeRowProps) => {
  const attribute = readFragment(AttributeRowFragment, attributeFragment);

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

interface AttributesTableProps {
  data: FragmentOf<typeof AttributesTableFragment>;
}

export const AttributesTable = ({ data }: AttributesTableProps) => {
  const connection = readFragment(AttributesTableFragment, data);

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