"use client";
import { allProducts } from "@/data/products";
import { useContextElement } from "@/context/Context";
import { useEffect, useState } from "react";
import { ProductCardWishlist } from "../shopCards/ProductCardWishlist";
import Link from "next/link";
import { ProductCard } from "../shopCards/ProductCard";

export default function Wishlist() {
	const { wishList } = useContextElement();
	const [wishListItems, setWishListItems] = useState([]);

	useEffect(() => {
		if (wishList.length) {
			
               const validIds = wishList.filter(id => /^\d+$/.test(id)); 

               if(validIds.length) {

                    fetch(`/api/productsdatabyids?ids=${wishList.join(",")}`)
                         .then((res) => res.json())
                         .then((data) => {
                              console.log(data.wishlistProducts); 
                              setWishListItems(data.wishlistProducts);
                         })
                         .catch((err) => console.error("Error fetching products:", err));

               } else setWishListItems([]); 
		} else {
			setWishListItems([]);
		}
	}, [wishList]);

	return (
		<section className='flat-spacing-2'>
			<div className='container'>
				<div
					className='grid-layout wrapper-shop'
					data-grid='grid-4'
				>
					{wishListItems.map((elm, i) => (
						<ProductCard product={elm} key={i}/>
					))}
				</div>
				{!wishListItems.length && (
					<>
						<div
							className='row align-items-center w-100'
							style={{ rowGap: "20px" }}
						>
							<div className='col-lg-3 col-md-6 fs-18'>
                                        Nu ai adăugat niciun produs la favorite încă.
							</div>
							<div className='col-lg-3  col-md-6'>
								<Link
									href={`/shop-default`}
									className='tf-btn btn-fill animate-hover-btn radius-3 w-100 justify-content-center'
								>
									Vezi produse
								</Link>
							</div>
						</div>
					</>
				)}
			</div>
		</section>
	);
}
