"use client";

import Link from "next/link";
import React, { useContext } from "react";
import { backendUrl } from "@/utils/axios";
import Image from "next/image";
import { useCurrency } from "@/app/contexts/currencyContext";
import ProductContext from "@/app/contexts/productContext";
import slugify from "slugify";

export default function ExploreSiddhaMala({ params }) {
  const { products, category } = useContext(ProductContext);
  const { formatPrice, isLoading } = useCurrency();

  const filteredProducts = products?.filter(
    (product) => product.product_category?.id == params.id
  );
  const selectedCategory = category?.find((cat) => cat.id == params.id);

  return (
    <section className="py-16 bg-gray-50">
      <div className="container mx-auto px-4">
        <h2 className="text-4xl font-bold text-center text-gray-800 mb-12">
          Explore{" "}
          {selectedCategory ? selectedCategory.category_name : "Products"}
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8">
          {filteredProducts?.map((product) => {
            // ✅ generate slug for debugging
            const slug = `${slugify(product.product_name, { lower: true })}-${
              product.id
            }`;
            console.log("Generated slug for product:", slug);

            return (
              <div
                key={product.id}
                className="bg-white shadow-lg rounded-lg overflow-hidden transition-transform transform hover:scale-105"
              >
                <Link href={`/products/${slug}`}>
                  <div className="relative w-full h-64 bg-gray-200">
                    <Image
                      src={`${backendUrl}${product?.images[0]?.image}`}
                      alt={product.product_name}
                      layout="fill"
                      objectFit="cover"
                      className="rounded-t-lg"
                    />
                  </div>
                </Link>
                <div className="p-5">
                  <h3 className="text-lg font-semibold text-gray-900 mb-2 truncate">
                    {product.product_name}
                  </h3>
                  {product.variants?.length > 0 ? (
                    <p className="text-lg font-bold text-green-600">
                      {isLoading
                        ? "Loading..."
                        : formatPrice(
                            Math.min(
                              ...product.variants.map(
                                (variant) => variant.price
                              )
                            )
                          )}
                    </p>
                  ) : (
                    <p className="text-md font-medium text-gray-500">
                      Price on request
                    </p>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}
