import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import SingleProductSkeleton from "./SingleProductSkeleton";
import axios from "axios";
import ProductImageGallery from "./ProductImageGallery";
import ProductDetails from "./ProductDetails";

export default function SingleProductPage() {
    const { id } = useParams();
    const API = import.meta.env.VITE_API_URL;

    const [product, setProduct] = useState(null);
    const [mainImage, setMainImage] = useState(null);
    const [isLoading, setIsLoading] = useState(true);

    /* ------------------- FETCH PRODUCT ------------------- */
    useEffect(() => {
        const fetchData = async () => {
            try {
                const res = await axios.get(`${API}/api/product/allproduct/${id}`);
                console.log("Product data →", res.data);
                setProduct(res.data);
                setMainImage(
                    res.data.media?.[0]?.url ? `${API}${res.data.media[0].url}` : null
                );
            } catch (err) {
                console.error(err);
            } finally {
                setIsLoading(false);
            }
        };
        fetchData();
    }, [id]);

    const addToCart = (productToAdd) => {
        console.log("Added to cart:", productToAdd.name);
    };

    const addToWishlist = (productToWishlist) => {
        console.log("Added to wishlist/Buy Now:", productToWishlist.name);
    };

    /* ------------------- RENDER LOGIC ------------------- */
    if (isLoading) return <SingleProductSkeleton />;

    if (!product) {
        return (
            <div className="flex justify-center items-center h-screen text-gray-500">
                Product not found
            </div>
        );
    }

    return (
        <div className="bg-white min-h-screen pb-32">
            {/* ------------------- MAIN LAYOUT ------------------- */}
            <div className="max-w-6xl mx-auto px-4 md:px-8 py-10 grid grid-cols-1 md:grid-cols-[100px_1fr_1fr] gap-8">
                {/* ------------------- LEFT: THUMBNAILS (DESKTOP ONLY) ------------------- */}
                <div className="hidden md:flex flex-col gap-3 overflow-y-auto max-h-[600px]">
                    {product?.media?.map((img, index) => (
                        <img
                            key={index}
                            src={`${API}${img.url}`}
                            alt={product.name}
                            onClick={() => setMainImage(`${API}${img.url}`)}
                            className={`w-20 h-20 object-cover rounded-xl cursor-pointer border-2 transition-transform duration-300 ${mainImage === `${API}${img.url}`
                                ? "border-none"
                                : "border-none"
                                }`}
                        />
                    ))}
                </div>

                {/* ------------------- MIDDLE: MAIN IMAGE + MOBILE THUMBNAILS + BUTTONS ------------------- */}
                <ProductImageGallery
                    product={product}
                    mainImage={mainImage}
                    setMainImage={setMainImage}
                    API={API}
                    addToCart={addToCart}
                    addToWishlist={addToWishlist}
                />

                {/* ------------------- RIGHT: PRODUCT DETAILS ------------------- */}
                <ProductDetails product={product} />
            </div>
        </div>
    );
}
