import type { ShopifyCollection } from "@reacteditor/field-shopify";
import { useCollectionProducts } from "@/editor/hooks/use-shopify-collections";
import { ProductCard } from "./product-card";
import { Typography } from "@/editor/theme/Typography";
import { Skeleton } from "@/components/ui/skeleton";

export type CollectionProps = {
  collection: ShopifyCollection | null;
  showDescription: "yes" | "no";
};

export function CollectionView({
  collection: selected,
  showDescription,
}: CollectionProps) {
  const handle = selected?.handle ?? "";
  const { collection, loading } = useCollectionProducts(handle, { first: 24 });

  if (!selected) {
    return (
      <section className="bg-background pb-24 pt-12 md:pt-20">
        <div className="container mx-auto max-w-7xl px-6">
          <header className="mx-auto mb-14 flex max-w-2xl flex-col items-center gap-3 text-center">
            <Skeleton className="h-3 w-24" />
            <Skeleton className="h-10 w-3/4" />
            {showDescription === "yes" ? (
              <Skeleton className="mt-1 h-5 w-2/3" />
            ) : null}
          </header>
          <div className="grid grid-cols-2 gap-x-6 gap-y-12 md:grid-cols-3 lg:grid-cols-4">
            {Array.from({ length: 8 }).map((_, i) => (
              <Skeleton key={i} className="aspect-[4/5] w-full" />
            ))}
          </div>
        </div>
      </section>
    );
  }

  const products = (collection?.products as any[] | undefined) ?? [];
  const description = collection?.description ?? selected.description;

  return (
    <section className="bg-background pb-24 pt-12 md:pt-20">
      <div className="container mx-auto max-w-7xl px-6">
        <header className="mx-auto mb-14 max-w-2xl text-center">
          <p className="mb-3 text-xs uppercase tracking-[0.2em] text-muted-foreground">
            Collection
          </p>
          <Typography variant="h1">
            {collection?.title ?? selected.title}
          </Typography>
          {showDescription === "yes" && description ? (
            <Typography variant="subtitle1" className="mt-4">
              {description}
            </Typography>
          ) : null}
        </header>

        <div className="grid grid-cols-2 gap-x-6 gap-y-12 md:grid-cols-3 lg:grid-cols-4">
          {loading
            ? Array.from({ length: 8 }).map((_, i) => (
                <Skeleton key={i} className="aspect-[4/5] w-full" />
              ))
            : products.map((p: any) => <ProductCard key={p.id} product={p} />)}
        </div>

        {!loading && products.length === 0 ? (
          <div className="mx-auto mt-12 max-w-md text-center text-sm text-muted-foreground">
            This collection has no products yet.
          </div>
        ) : null}
      </div>
    </section>
  );
}
