'use client';

import React from 'react';
import { useParams } from 'next/navigation';
import { useCollectionProducts } from '@/hooks/use-shopify-collections';
import ProductCard from './product-card';
import { Button } from '@/components/ui/button';

const GRID_CLASSES =
  'grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-x-8 gap-y-16';

const CollectionTitle: React.FC<{ title: string }> = ({ title }) => (
  <h2 className="text-center text-2xl md:text-3xl font-normal max-w-3xl mx-auto text-foreground mb-16">
    {title}
  </h2>
);

const CollectionDetail: React.FC = () => {
  const params = useParams();
  const handle = params?.handle as string;

  const { collection, loading, error, refetch } = useCollectionProducts(handle);

  // Format title from handle
  const formattedTitle = handle
    ? handle.replace(/-/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())
    : 'Collection';

  if (loading) {
    return (
      <div className="py-16 bg-background">
        <div className="max-w-screen-2xl mx-auto px-8">
          <CollectionTitle title={formattedTitle} />

          {/* Loading Skeleton */}
          <div className={GRID_CLASSES}>
            {Array.from({ length: 8 }).map((_, index) => (
              <div key={index} className="animate-pulse">
                <div className="aspect-square bg-zinc-100"></div>
                <div className="pt-4 space-y-2">
                  <div className="h-4 bg-zinc-200 w-4/5"></div>
                  <div className="h-4 bg-zinc-200 w-1/4"></div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="py-16 bg-background">
        <div className="max-w-screen-2xl mx-auto px-8 text-center">
          <CollectionTitle title={formattedTitle} />
          <p className="text-sm text-muted-foreground mb-6">{error}</p>
          <Button onClick={() => refetch()} variant="outline">
            Try Again
          </Button>
        </div>
      </div>
    );
  }

  const products = collection?.products || [];
  const title = collection?.title || formattedTitle;

  return (
    <div className="py-16 bg-background">
      <div className="max-w-screen-2xl mx-auto px-8">
        <CollectionTitle title={title} />

        {products.length === 0 ? (
          <p className="text-center text-sm text-muted-foreground">
            This collection doesn&apos;t have any products yet.
          </p>
        ) : (
          <div className={GRID_CLASSES}>
            {products.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default CollectionDetail;
