"use client"
import Image from "next/image"
import { ShoppingCart, HardHat, ChevronRight } from "lucide-react"
import Link from "next/link"
import { useLocale } from "next-intl"
import { useTranslations } from "next-intl"
import { useEffect } from "react"
import { FastAverageColor } from 'fast-average-color';




export default function ProductCard({ product }) {
  const { title, brand, category, price, discount, images, slug,documentId } = product
  const isValidPrice = typeof price === "number" && !isNaN(price)
  const isValidDiscount = typeof discount === "number" && !isNaN(discount) && discount > 0 && discount <= 100

  const displayPrice = isValidPrice ? price : 0
  const discountedPrice =
    isValidPrice && isValidDiscount ? displayPrice - (displayPrice * discount) / 100 : displayPrice

  const CategoryIcon = category.slug === "fmcg" ? ShoppingCart : HardHat

  const fallbackBrandLetter = brand?.title ? brand.title.charAt(0).toUpperCase() : "#"
  const locale = useLocale()
  const t = useTranslations("")
  useEffect(() => {
    const fac = new FastAverageColor();
    if (images?.[0]?.url) {
      fac.getColorAsync(images?.[0]?.url)
        .then(color => {
          const container = document.querySelector(`#container-${documentId}`)
          // document.body.style.background = color.rgba
          // document.body.style.color = color.isDark ? '#fff' : '#000';
          container.style.backgroundColor = color.rgba;
          // container.style.color = color.isDark ? '#fff' : '#000';
        })
        .catch(e => {
          console.log(e);
        });
    }
  }, [])
  return (
    <div className="bg-white rounded-lg shadow-md overflow-hidden" dir={locale === "en" ? "ltr" : "rtl"} >
      <div className="relative h-48 w-full overflow-hidden rounded-lg " id={`container-${documentId}`}>
        <Image src={images?.[0]?.url} alt={images?.[0]?.alternativeText ?? ""} layout="fill" className="object-contain border" />
        {isValidDiscount && (
          <div className="absolute top-2 right-2 bg-red-500 text-white text-xs font-semibold px-2 py-1 rounded-full">
            {discount}% OFF
          </div>
        )}
      </div>
      <div className="p-4">

        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center space-x-2 w-2/3">
            {brand?.title &&
              <>
                <div className="size-6 min-w-6 rounded-full overflow-hidden relative aspect-square">
                  {brand?.image?.url ? (
                    <Image src={brand?.image?.url} alt={brand?.image.alternativeText ?? ""} fill className=" object-cover aspect-square" />
                  ) : (
                    <div className="h-full w-full flex items-center justify-center bg-gray-200 text-gray-700 font-semibold">
                      {fallbackBrandLetter}
                    </div>
                  )}
                </div>

                <span className={`text-sm font-medium w-full px-1 ${locale === "en" ? "text-left" : "text-right"}`}>{brand?.title || ""}</span>
              </>
            }
          </div>
          <div className={`flex items-center text-sm text-gray-500 w-1/3 ${locale === "en" ? "flex-row-reverse justify-start" : "flex-row justify-end"}`} >
            <CategoryIcon className="size-4 min-h-4 min-w-4 mx-1 aspect-square" />
            <span>{category.slug === "fmcg" ? t("HomePage.Sides.fmcg.title") : t("HomePage.Sides.construction.title")}</span>
          </div>
        </div>
        <h3 className={`text-lg font-semibold mb-2 line-clamp-2 min-h-14 ${locale === "en" ? "text-left" : "text-right"}`} >{title}</h3>
        <div className="flex items-center justify-between mb-4">
          <div>
            {isValidPrice ? (
              <>
                <span className="text-xl font-bold">${discountedPrice.toFixed(2)}</span>
                {isValidDiscount && (
                  <span className="text-sm text-gray-500 line-through ml-2">${displayPrice.toFixed(2)}</span>
                )}
              </>
            ) : (
              <span className="text-xl font-bold"></span>
            )}
          </div>
        </div>
        <Link href={`/product/${slug}`.toLowerCase()}
          className={`w-full flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors ${locale === "en" ? "flex-row" : "flex-row-reverse"}`}>
          {t("Utils.moreDetail")}
          <ChevronRight className="h-4 w-4 ml-2" />
        </Link>
      </div>
    </div>
  )
}

export function ProductCardSkeleton() {
  return (
    <div className="bg-white rounded-lg shadow-md overflow-hidden">
      {/* Image placeholder */}
      <div className="relative h-48 w-full bg-gray-200 animate-pulse" />

      <div className="p-4">
        {/* Brand and category placeholder */}
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center space-x-2">
            <div className="h-6 w-6 rounded-full bg-gray-300 animate-pulse" />
            <div className="h-4 w-24 bg-gray-300 rounded animate-pulse" />
          </div>
          <div className="h-4 w-20 bg-gray-300 rounded animate-pulse" />
        </div>

        {/* Product name placeholder */}
        <div className="h-6 w-3/4 bg-gray-300 rounded animate-pulse mb-2" />

        {/* Price placeholder */}
        <div className="flex items-center justify-between mb-4">
          <div className="h-8 w-24 bg-gray-300 rounded animate-pulse" />
        </div>

        {/* Button placeholder */}
        <div className="h-10 w-full bg-gray-300 rounded animate-pulse" />
      </div>
    </div>
  )
}