import { Badge, DescriptionCard, Table } from "@tailor-platform/app-shell";
import { graphql, type FragmentOf, readFragment } from "@/graphql";

export const ProductDetailFragment = graphql(`
  fragment ProductDetail on Product {
    id
    name
    code
    description
    unit {
      name
      symbol
    }
    status
    createdAt
    updatedAt
    productCategoryAssignments {
      edges {
        node {
          id
          productCategory {
            id
            name
          }
        }
      }
    }
    productAttributeAssignments {
      edges {
        node {
          id
          productAttribute {
            name
          }
          productAttributeValue {
            label
          }
        }
      }
    }
    productVariants {
      edges {
        node {
          id
          axisValueKey
          item {
            sku
          }
        }
      }
    }
  }
`);

interface ProductDetailProps {
  product: FragmentOf<typeof ProductDetailFragment>;
}

export const ProductDetail = ({ product: productFragment }: ProductDetailProps) => {
  const product = readFragment(ProductDetailFragment, productFragment);

  const attributeAssignments = product.productAttributeAssignments?.edges?.map((e) => e.node) ?? [];
  const variants = product.productVariants?.edges?.map((e) => e.node) ?? [];

  const categoryNames =
    product.productCategoryAssignments?.edges
      ?.map((e) => e.node.productCategory?.name)
      .filter((name): name is string => name != null) ?? [];

  const displayData = {
    ...product,
    unitName: product.unit ? `${product.unit.name} (${product.unit.symbol})` : "—",
    categoryNames,
  };

  return (
    <div className="flex flex-col gap-4">
      <DescriptionCard
        data={displayData}
        title="Product Information"
        columns={3}
        fields={[
          { key: "name", label: "Name" },
          { key: "code", label: "Code", meta: { copyable: true } },
          { key: "description", label: "Description" },
          { key: "unitName", label: "Unit" },
          {
            key: "status",
            label: "Status",
            type: "badge",
            meta: {
              badgeVariantMap: {
                ACTIVE: "success",
                DRAFT: "info",
                ARCHIVED: "neutral",
              },
            },
          },
          {
            key: "categoryNames",
            label: "Categories",
            type: "badge",
            meta: { sentenceCaseBadges: false, maxVisible: 6 },
          },
          { type: "divider" },
          {
            key: "createdAt",
            label: "Created At",
            type: "date",
            meta: { dateFormat: "medium" },
          },
          {
            key: "updatedAt",
            label: "Updated At",
            type: "date",
            meta: { dateFormat: "relative" },
          },
        ]}
      />
      <div className="rounded-lg border p-4">
        <h3 className="mb-3 text-sm font-medium">Assigned Attributes</h3>
        {attributeAssignments.length > 0 ? (
          <div className="space-y-2">
            {Object.entries(
              attributeAssignments.reduce<
                Record<string, { attrName: string; values: { id: string; label: string }[] }>
              >((acc, a) => {
                const attrName = a.productAttribute?.name ?? "—";
                if (!acc[attrName]) acc[attrName] = { attrName, values: [] };
                acc[attrName].values.push({
                  id: a.id,
                  label: a.productAttributeValue?.label ?? "—",
                });
                return acc;
              }, {}),
            ).map(([attrName, group]) => (
              <div key={attrName}>
                <p className="mb-1 text-xs font-medium text-muted-foreground">{attrName}</p>
                <div className="flex flex-wrap gap-1">
                  {group.values.map((v) => (
                    <Badge key={v.id}>{v.label}</Badge>
                  ))}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-muted-foreground text-sm">No attributes assigned</p>
        )}
      </div>
      <div className="rounded-lg border p-4">
        <h3 className="mb-3 text-sm font-medium">Variants ({variants.length})</h3>
        {variants.length > 0 ? (
          <Table.Root>
            <Table.Header>
              <Table.Row>
                <Table.Head>SKU</Table.Head>
                <Table.Head>Axis Value Key</Table.Head>
              </Table.Row>
            </Table.Header>
            <Table.Body>
              {variants.map((v) => (
                <Table.Row key={v.id}>
                  <Table.Cell>{v.item?.sku ?? "—"}</Table.Cell>
                  <Table.Cell className="text-muted-foreground text-xs">
                    {v.axisValueKey}
                  </Table.Cell>
                </Table.Row>
              ))}
            </Table.Body>
          </Table.Root>
        ) : (
          <p className="text-muted-foreground text-sm">No variants generated</p>
        )}
      </div>
    </div>
  );
};
