"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useCart } from "@/context/CartContext";

interface Product {
  _id: string;
  title: string;
  price: number;
  photoUrl?: string;
  images?: string[];
  shortDescription?: string;
  slug?: string;
}

export default function FeaturedProducts() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const { addItem, items, updateQuantity, removeItem } = useCart();

  useEffect(() => {
    const fetchFeaturedProducts = async () => {
      try {
        const response = await fetch("/api/products/featured?limit=8");
        const data = await response.json();
        setProducts(data.products || []);
      } catch (error) {
        console.error("Error fetching featured products:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchFeaturedProducts();
  }, []);

  const getQty = (id: string) => items.find((i) => i.productId === id)?.quantity || 0;
  const inc = (p: Product) => addItem({ productId: p._id, title: p.title, price: p.price || 0, quantity: 1, sku: p.slug || "" });
  const dec = (id: string) => {
    const ex = items.find((i) => i.productId === id);
    if (!ex) return;
    const next = ex.quantity - 1;
    if (next <= 0) removeItem(id); else updateQuantity(id, next);
  };

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-12">
        <div className="text-center">Loading featured products...</div>
      </div>
    );
  }

  if (products.length === 0) {
    return null; // Don't show section if no products
  }

  return (
    <section className="container mx-auto px-4 py-12">
      <div className="text-center mb-8">
        <h2 className="text-3xl md:text-4xl font-bold text-gray-900 mb-2">
          Featured Products
        </h2>
        <p className="text-gray-600">Discover our handpicked selection</p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4">
        {products.map((product) => {
          const imageUrl = (product as any).photoThumb || (product as any).thumbnails?.[0] || product.images?.[0] || product.photoUrl || "/placeholder-image.png";
          const productUrl = product.slug 
            ? `/product/${product.slug}` 
            : `/product/${product._id}`;
          const qty = getQty(product._id);

          return (
            <div
              key={product._id}
              className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition-shadow duration-300 group flex flex-col"
            >
              <Link href={productUrl}>
                <div className="relative h-48 overflow-hidden bg-gray-100">
                  <img
                    src={imageUrl}
                    alt={product.title}
                    className="w-full h-full object-contain p-2"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src = "/placeholder-image.png";
                    }}
                  />
                  <div className="absolute top-2 right-2 bg-green-500 text-white px-2 py-1 rounded text-xs font-semibold">
                    Featured
                  </div>
                </div>
              </Link>

              <div className="p-4 flex flex-col flex-1">
                <Link href={productUrl}>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2 line-clamp-2 hover:text-blue-600 transition">
                    {product.title}
                  </h3>
                </Link>

                {product.shortDescription && (
                  <p className="text-sm text-gray-600 mb-3 line-clamp-2">
                    {product.shortDescription}
                  </p>
                )}

                <div className="flex items-center justify-between gap-2 mt-auto pt-2">
                  <span className="text-lg font-bold text-green-600">
                    ${product.price?.toFixed(2) || "0.00"}
                  </span>
                  {qty > 0 ? (
                    <div className="flex items-center gap-2">
                      <button
                        onClick={(e) => { e.preventDefault(); dec(product._id); }}
                        className="w-8 h-8 rounded border border-gray-300 bg-white hover:bg-gray-100 flex items-center justify-center"
                      >
                        −
                      </button>
                      <span className="min-w-[1.5rem] text-center text-sm font-semibold">{qty}</span>
                      <button
                        onClick={(e) => { e.preventDefault(); inc(product); }}
                        className="w-8 h-8 rounded border border-gray-300 bg-white hover:bg-gray-100 flex items-center justify-center"
                      >
                        +
                      </button>
                    </div>
                  ) : (
                    <button
                      onClick={(e) => { e.preventDefault(); inc(product); }}
                      className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold rounded-lg transition whitespace-nowrap"
                    >
                      Add to Cart
                    </button>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="text-center mt-8">
        <Link
          href="/shop"
          className="inline-block px-6 py-3 bg-gray-900 hover:bg-gray-800 text-white font-semibold rounded-lg transition"
        >
          View All Products
        </Link>
      </div>
    </section>
  );
}

