"use client";

import { Suspense, use, useCallback } from "react";
import { useRouter } from "next/navigation";
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import ProductDetailCard from "@/components/ecommerce/productDetail/ProductDetailCard";
import ProductCart from "@/components/ecommerce/cart/ProductCart";
import { useProductDetail } from "@/hooks/useProductDetail";
import { useCart } from "@/hooks/useCart";
import { useCheckout } from "@/hooks/useCheckout";
import NavbarLayoutFloatingOverlay from '@/components/navbar/NavbarLayoutFloatingOverlay/NavbarLayoutFloatingOverlay';
import FooterMedia from '@/components/sections/footer/FooterMedia';
import Link from 'next/link';

interface ProductPageProps {
    params: Promise<{ id: string }>;
}

export default function ProductPage({ params }: ProductPageProps) {
    return (
        <Suspense fallback={null}>
            <ProductPageContentWrapper params={params} />
        </Suspense>
    );
}

function ProductPageContentWrapper({ params }: ProductPageProps) {
    const { id } = use(params);
    const router = useRouter();

    const {
        product,
        isLoading,
        images,
        meta,
        variants,
        quantityVariant,
        selectedQuantity,
        createCartItem,
    } = useProductDetail(id);

    const {
        items: cartItems,
        isOpen: cartOpen,
        setIsOpen: setCartOpen,
        addItem,
        updateQuantity,
        removeItem,
        total: cartTotal,
        getCheckoutItems,
    } = useCart();

    const { buyNow, checkout, isLoading: isCheckoutLoading } = useCheckout();

    const handleAddToCart = useCallback(() => {
        const item = createCartItem();
        if (item) {
            addItem(item);
        }
    }, [createCartItem, addItem]);

    const handleBuyNow = useCallback(() => {
        if (product) {
            buyNow(product, selectedQuantity);
        }
    }, [product, selectedQuantity, buyNow]);

    const handleCheckout = useCallback(async () => {
        if (cartItems.length === 0) return;

        const currentUrl = new URL(window.location.href);
        currentUrl.searchParams.set("success", "true");

        await checkout(getCheckoutItems(), { successUrl: currentUrl.toString() });
    }, [cartItems, checkout, getCheckoutItems]);

    const content = () => {
        if (isLoading) {
            return (
                <main className="min-h-screen flex items-center justify-center pt-20">
                    <p className="text-foreground">Loading product...</p>
                </main>
            )
        }
        if (!product) {
            return (
                <main className="min-h-screen flex items-center justify-center pt-20">
                    <div className="text-center">
                        <p className="text-foreground mb-4">Product not found</p>
                        <button
                            onClick={() => router.push("/shop")}
                            className="primary-button px-6 py-2 rounded-theme text-primary-cta-text"
                        >
                            Back to Shop
                        </button>
                    </div>
                </main>
            )
        }
        return (
            <div id="product-detail-card" data-section="product-detail-card">
                <ProductDetailCard
                    layout="page"
                    name={product.name}
                    price={product.price}
                    salePrice={meta.salePrice}
                    rating={product.rating || 0}
                    description={product.description}
                    images={images}
                    variants={variants.length > 0 ? variants : undefined}
                    quantity={quantityVariant}
                    ribbon={meta.ribbon}
                    inventoryStatus={meta.inventoryStatus}
                    inventoryQuantity={meta.inventoryQuantity}
                    sku={meta.sku}
                    buttons={[
                        { text: "Add To Cart", onClick: handleAddToCart },
                        { text: "Buy Now", onClick: handleBuyNow },
                    ]}
                />
            </div>
        )
    }

    return (
        <ThemeProvider
            defaultButtonVariant="text-stagger"
            defaultTextAnimation="entrance-slide"
            borderRadius="soft"
            contentWidth="mediumSmall"
            sizing="largeSmall"
            background="noise"
            cardStyle="solid"
            primaryButtonStyle="double-inset"
            secondaryButtonStyle="glass"
            headingFontWeight="normal"
        >
            <div id="nav" data-section="nav">
                <NavbarLayoutFloatingOverlay
                    navItems={[{ name: "Home", id: "/" }]}
                    brandName="Dobry Khlib"
                    button={{ text: `Cart (${cartItems.length})`, onClick: () => setCartOpen(true) }}
                />
            </div>
            {content()}
            <div id="product-cart" data-section="product-cart">
                <ProductCart
                    isOpen={cartOpen}
                    onClose={() => setCartOpen(false)}
                    items={cartItems}
                    onQuantityChange={updateQuantity}
                    onRemove={removeItem}
                    total={`$${cartTotal}`}
                    buttons={[
                        {
                            text: isCheckoutLoading ? "Processing..." : "Check Out",                            onClick: handleCheckout,
                        },
                    ]}
                />
            </div>
            <div id="footer" data-section="footer">
                <FooterMedia 
                    imageSrc="https://img.b2bpic.net/free-photo/white-cheese-bread-with-eggs_140725-3991.jpg?_wi=5"
                    imageAlt="Assortment of freshly baked Ukrainian goods"
                    columns={[
                        {title: "Bakery", items: [{label: "Our Story", href: "/#about"}, {label: "Products", href: "/#products"}, {label: "Order Online", href: "/#products"}]},
                        {title: "Support", items: [{label: "FAQ", href: "/#faq"}, {label: "Contact Us", href: "/#contact"}]},
                        {title: "Legal", items: [{label: "Privacy Policy", href: "/privacy"}, {label: "Terms of Service", href: "/terms"}]}
                    ]}
                    logoText="Dobry Khlib"
                    copyrightText="© 2024 Dobry Khlib. All rights reserved."
                    onPrivacyClick={() => console.log('Privacy Policy clicked')}
                />
            </div>
        </ThemeProvider>
    );
}
