"use client";
import React, { useMemo } from "react";
import Image from "next/image";
import Link from "next/link";
import { Card } from "../ui/card";
import { Badge } from "../ui/badge";
import { Container } from "../ui/container";
import { TypographyH3 } from "../ui/typography";
import { useProducts } from "@/hooks/useProducts";
import { convertApiProductToProduct } from "@/types/api";

interface YouMightAlsoLikeProps {
  categoryId?: number;
  currentProductId?: number;
  limit?: number;
}

const renderStars = (rating: number) => {
  const fullCount = Math.floor(rating);
  const hasHalf = rating - fullCount >= 0.5;
  const stars = Array.from({ length: 5 }).map((_, i) => {
    let src = "/assets/icons/full-star.svg";
    let alt = "full-star";
    let className = "w-[18.49px] h-[18.49px]";

    if (i < fullCount) {
      src = "/assets/icons/full-star.svg";
      alt = "full-star";
    } else if (i === fullCount && hasHalf) {
      src = "/assets/icons/half-star.svg";
      alt = "half-star";
    } else {
      src = "/assets/icons/full-star.svg";
      alt = "empty-star";
      className = className + " opacity-30";
    }

    return (
      <Image
        key={i}
        src={src}
        alt={alt}
        width={16}
        height={16}
        className={className}
      />
    );
  });
  return <div className="flex items-center gap-1">{stars}</div>;
};

const YouMightAlsoLike: React.FC<YouMightAlsoLikeProps> = ({ 
  categoryId, 
  currentProductId,
  limit = 4 
}) => {
  // Fetch products from the same category
  const { products: apiProducts, loading } = useProducts({
    category_id: categoryId,
    enableCache: true,
    autoFetch: true,
  });

  // Convert and filter out current product
  const relatedProducts = useMemo(() => {
    return apiProducts
      .filter(p => p.id !== currentProductId)
      .slice(0, limit)
      .map(convertApiProductToProduct);
  }, [apiProducts, currentProductId, limit]);

  // Show skeleton while loading
  if (loading && relatedProducts.length === 0) {
    return (
      <div className="px-4 md:px-6 mb-28 md:mb-[133px]">
        <Container>
          <TypographyH3 className="text-center text-[30px] sm:text-[36px] md:text-[48px] leading-[38px] sm:leading-[46px] md:leading-[73px] font-extrabold prompt">
            قد يعجبك <span className="text-[#F5411C]">أيضًا</span>
          </TypographyH3>
          <div className="w-full mt-8 md:mt-12 grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-6 md:gap-5">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="animate-pulse">
                <div className="bg-gray-200 rounded-[20px] h-[298px] mb-3"></div>
                <div className="h-6 bg-gray-200 rounded mb-2"></div>
                <div className="h-4 bg-gray-200 rounded w-3/4"></div>
              </div>
            ))}
          </div>
        </Container>
      </div>
    );
  }

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

  return (
    <div className="px-4 md:px-6 mb-28 md:mb-[133px]">
      <Container>
        <TypographyH3 className="text-center text-[30px] sm:text-[36px] md:text-[48px] leading-[38px] sm:leading-[46px] md:leading-[73px] font-extrabold prompt">
          قد يعجبك <span className="text-[#F5411C]">أيضًا</span>
        </TypographyH3>

        <div className="w-full mt-8 md:mt-12 grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-6 md:gap-5">
          {relatedProducts.map((p) => (
            <Link key={p.id} href={`/products/${p.slug}`}>
              <Card className="w-full bg-transparent shadow-none p-0 hover:shadow-lg transition-shadow duration-200 cursor-pointer">
                <div className="bg-[#F0EEED] rounded-[20px] h-[298px] overflow-hidden w-full mb-3 md:mb-4 flex items-center justify-center relative">
                  <Image
                    src={p.imageSrc}
                    alt={p.title}
                    fill
                    className="object-cover"
                    unoptimized={p.imageSrc.startsWith('data:image')}
                  />
                </div>

              <TypographyH3 className="text-[20px] leading-6 font-bold line-clamp-2">{p.title}</TypographyH3>

              <div className="mt-2.5 flex items-center gap-[13px]">
                {renderStars(p.rating ?? 0)}
                <span className="">{(p.rating ?? 0).toFixed(1)}/5</span>
              </div>

              <div className="mt-2.5 flex items-center gap-2">
                <span className="text-[24px] leading-[29px] font-bold">
                  {p.price}
                </span>
                {p.oldPrice ? (
                  <span className="text-[#00000066] line-through text-[24px] leading-[29px] font-bold">
                    {p.oldPrice}
                  </span>
                ) : null}
                {p.saleLabel ? (
                  <Badge
                    variant="secondary"
                    className="bg-[#FF33331A] text-[#FF3333] border-0 rounded-full text-[12px] leading-4 font-medium px-[13.5px] py-1.5"
                  >
                    {p.saleLabel}
                  </Badge>
                ) : null}
              </div>
              </Card>
            </Link>
          ))}
        </div>
      </Container>
    </div>
  );
};

export default YouMightAlsoLike;