"use client";

import Link from "next/link";
import Image from "next/image";
import { useEffect, useState } from "react";
import { createClient } from "../../lib/supabase/client";

type Product = {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  price: number;
  is_available: boolean;
  featured_image_url: string | null;
};

const productImages: Record<string, string> = {
  "pelcy-granola": "/products/granola.jpg",
  "pelcy-parfait": "/products/parfait.jpg",
  "pelcy-yoghurt": "/products/yoghurt.jpg",
  "fresh-fruit-bowl": "/products/fruit-bowl.jpg",
};

export default function ProductGrid() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState("");

  useEffect(() => {
    async function loadProducts() {
      const supabase = createClient();

      const { data, error } = await supabase
        .from("products")
       .select(
  "id, name, slug, description, price, is_available, featured_image_url"
)
        .eq("is_available", true)
        .order("name");

      if (error) {
        console.error(error);
        setErrorMessage(error.message);
      } else {
        setProducts(data ?? []);
      }

      setLoading(false);
    }

    loadProducts();
  }, []);

  if (loading) {
    return (
      <div className="rounded-3xl bg-white p-8 text-center">
        <p className="font-bold">
          Loading PELCY products...
        </p>
      </div>
    );
  }

  if (errorMessage) {
    return (
      <div className="rounded-3xl bg-red-100 p-8 text-red-700">
        <p className="font-bold">
          Unable to load products.
        </p>

        <p className="mt-2 text-sm">
          {errorMessage}
        </p>
      </div>
    );
  }

  if (products.length === 0) {
    return (
      <div className="rounded-3xl bg-white p-8 text-center">
        <p>No PELCY products are available yet.</p>
      </div>
    );
  }

  return (
    <div className="grid gap-7 sm:grid-cols-2 lg:grid-cols-4">
      {products.map((product) => {
        const image =
  product.featured_image_url ||
  productImages[product.slug] ||
  "/products/hero.jpg";

        return (
          <article
            key={product.id}
            className="group overflow-hidden rounded-[28px] bg-white shadow-sm transition hover:-translate-y-2 hover:shadow-xl"
          >
            <div className="relative aspect-square overflow-hidden">
             <Image
  src={image}
  alt={product.name}
  fill
  sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw"
  className="object-cover transition duration-500 group-hover:scale-105"
/>
            </div>

            <div className="p-6">
              <h3 className="text-xl font-black">
                {product.name}
              </h3>

              <p className="mt-2 min-h-[72px] text-sm leading-6 text-black/55">
                {product.description ??
                  "Fresh PELCY product."}
              </p>

              <div className="mt-6 flex items-center justify-between gap-3">
                <span className="font-black">
                  ₦
                  {Number(
                    product.price
                  ).toLocaleString()}
                </span>

               <Link
  href={`/products/${product.slug}`}
  className="rounded-full bg-[#2b2118] px-4 py-2 text-sm font-bold text-white"
>
  View
</Link>
              </div>
            </div>
          </article>
        );
      })}
    </div>
  );
}