import Banner from "@/components/banner";
import {
  fetchCategoryById,
  fetchSubcategoriesByCategory,
  getImageUrl,
} from "@/lib/api";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ChevronRight } from "lucide-react";

interface PageProps {
  params: { categoryId: string };
}

export default async function CategoryPage({ params }: PageProps) {
  const categoryId = params.categoryId;

  try {
    // Fetch data in parallel
    const [categoryData, subcategories] = await Promise.all([
      fetchCategoryById(categoryId),
      fetchSubcategoriesByCategory(categoryId),
    ]);

    if (!categoryData) {
      return notFound();
    }

    return (
      <>
        <Banner imageSrc={getImageUrl(categoryData.banner)} height={400}>
          <div className="text-center text-white">
            <h1 className="text-5xl font-bold mb-4">{categoryData.name}</h1>
          </div>
        </Banner>

        <section className="px-4 md:px-8 py-16 text-black">
          <div className="container max-w-7xl mx-auto">
            <h2 className="text-3xl font-bold mb-2">Subcategories</h2>
            <div className="flex gap-2 mb-8">
              <Link href="/products" className="hover:underline duration-300">
                Products
              </Link>
              <ChevronRight className="h-4 w-4" />
              <span>{categoryData.name}</span>
            </div>
            {subcategories && subcategories.length > 0 ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                {subcategories.map((subcategory: any) => (
                  <SubcategoryCard
                    key={subcategory.id}
                    subcategory={subcategory}
                  />
                ))}
              </div>
            ) : (
              <div className="text-center py-16">
                <p className="text-gray-500 text-lg">No subcategories found.</p>
                <Link
                  href="/products"
                  className="mt-4 inline-block bg-red-600 hover:bg-red-700 text-white px-6 py-2 rounded-lg transition-colors"
                >
                  Browse All Categories
                </Link>
              </div>
            )}
          </div>
        </section>
      </>
    );
  } catch (error) {
    console.log(error);
    return notFound();
  }
}

function SubcategoryCard({ subcategory }: { subcategory: any }) {
  const productCount = subcategory.products?.length || 0;

  return (
    <Link
      href={`/products/subcategory/${subcategory.id}`}
      className="block bg-white border border-gray-200 rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-all group"
    >
      <div className="relative h-48 overflow-hidden">
        <Image
          src={getImageUrl(subcategory.banner) || "/placeholder.svg"}
          alt={subcategory.name}
          fill
          className="object-cover transition-transform duration-300 group-hover:scale-105"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent flex items-end">
          <h2 className="text-white text-xl font-bold p-6">
            {subcategory.name}
          </h2>
        </div>
      </div>

      <div className="p-6">
        <p className="text-gray-700 mb-4 line-clamp-2">
          {subcategory.short_description}
        </p>

        <div className="flex items-center justify-between mt-4">
          <span className="text-sm bg-orange-100 text-orange-600 px-3 py-1 rounded-full">
            {productCount} {productCount === 1 ? "product" : "products"}
          </span>

          <div className="flex items-center text-red-600 font-medium">
            <span>View Products</span>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5 ml-2 transition-transform group-hover:translate-x-1"
              viewBox="0 0 20 20"
              fill="currentColor"
            >
              <path
                fillRule="evenodd"
                d="M10.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L12.586 11H5a1 1 0 110-2h7.586l-2.293-2.293a1 1 0 010-1.414z"
                clipRule="evenodd"
              />
            </svg>
          </div>
        </div>
      </div>
    </Link>
  );
}
