'use client';

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

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

  const { collection, loading, error } = 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="pt-4 pb-16">
        <div className="container mx-auto px-4">
          <h2 className="text-4xl font-medium tracking-tight text-center mb-12 text-gray-900 font-heading">
            {formattedTitle}
          </h2>

          {/* Loading Skeleton */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
            {Array.from({ length: 6 }).map((_, index) => (
              <div key={index} className="animate-pulse">
                <div className="aspect-square bg-gray-200"></div>
                <div className="mt-3 h-4 w-2/3 bg-gray-200 rounded"></div>
                <div className="mt-2 h-4 w-1/4 bg-gray-200 rounded"></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="pt-4 pb-16">
        <div className="container mx-auto px-4 py-32 text-center">
          <h2 className="text-2xl font-medium tracking-tight text-gray-900 font-heading mb-3">
            Collection Not Found
          </h2>
          <p className="text-gray-500 max-w-md mx-auto">
            The collection you are looking for does not exist or is no longer
            available.
          </p>
        </div>
      </div>
    );
  }

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

  return (
    <div className="pt-4 pb-16">
      <div className="container mx-auto px-4">
        <h2 className="text-4xl font-medium tracking-tight text-center mb-12 text-gray-900 font-heading">
          {title}
        </h2>

        {products.length === 0 ? (
          <div className="text-center py-20">
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              No Products in Collection
            </h3>
            <p className="text-gray-500">
              This collection doesn&apos;t have any products yet.
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
            {products.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default CollectionDetail;
