"use client";

import { Suspense, use, useCallback } from "react";
import { useRouter } from "next/navigation";
import ReactLenis from "lenis/react";
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarLayoutFloatingInline from "@/components/navbar/NavbarLayoutFloatingInline";
import FooterBase from '@/components/sections/footer/FooterBase';
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";

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

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

function ProductPageContent({ 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]);

    if (isLoading) {
        return (
            <ThemeProvider
                defaultButtonVariant="hover-magnetic"
                defaultTextAnimation="background-highlight"
                borderRadius="rounded"
                contentWidth="medium"
                sizing="mediumLarge"
                background="fluid"
                cardStyle="subtle-shadow"
                primaryButtonStyle="primary-glow"
                secondaryButtonStyle="glass"
                headingFontWeight="semibold"
            >
                <ReactLenis root>
                    <div id="navbar" data-section="navbar">
                        <NavbarLayoutFloatingInline
                            navItems={[{ name: "Home", id: "/" }, { name: "Shop", id: "/shop" }]}
                            brandName="ProTech"
                            button={{ text: "Cart", onClick: () => setCartOpen(true) }}
                            className="py-4 px-6"
                            navItemClassName="text-foreground hover:text-primary-cta"
                            buttonClassName="bg-primary-cta text-secondary-cta px-6 py-3 rounded-full hover:scale-105 transition-transform duration-300"
                            buttonTextClassName="font-semibold"
                        />
                    </div>
                    <div id="loading-section" data-section="loading-section">
                        <main className="min-h-screen flex items-center justify-center pt-20">
                            <p className="text-foreground">Loading product...</p>
                        </main>
                    </div>
                    <div id="footer" data-section="footer">
                        <FooterBase
                            columns={[
                                { title: "Services", items: [{ label: "Furnace Repair", href: "#services" }, { label: "AC Replacement", href: "#services" }, { label: "Emergency HVAC", href: "#services" }, { label: "Maintenance Plans", href: "#maintenance-plan" }] },
                                { title: "Company", items: [{ label: "About Us", href: "#about" }, { label: "Why Choose Us", href: "#why-choose-us" }, { label: "Contact", href: "#contact" }, { label: "Reviews", href: "#social-proof" }] },
                                { title: "Legal", items: [{ label: "Privacy Policy", href: "/privacy" }, { label: "Terms of Service", href: "/terms" }] }
                            ]}
                            logoText="ProTech Heating & Cooling"
                            copyrightText="© 2024 ProTech Heating & Cooling Inc. All rights reserved."
                            className="py-12 md:py-16 lg:py-20 bg-foreground text-background-accent"
                            containerClassName="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 grid grid-cols-1 md:grid-cols-4 gap-8"
                            logoTextClassName="text-2xl font-bold text-background mb-6"
                            columnsClassName="grid grid-cols-2 md:grid-cols-3 gap-8 col-span-full md:col-span-3"
                            columnTitleClassName="text-lg font-semibold text-background mb-4"
                            columnItemClassName="text-background/80 hover:text-primary-cta transition-colors duration-200"
                            copyrightContainerClassName="mt-8 md:mt-0 text-background/60 text-sm"
                            copyrightTextClassName="mb-2"
                            privacyButtonClassName="text-primary-cta hover:underline"
                        />
                    </div>
                </ReactLenis>
            </ThemeProvider>
        );
    }

    if (!product) {
        return (
            <ThemeProvider
                defaultButtonVariant="hover-magnetic"
                defaultTextAnimation="background-highlight"
                borderRadius="rounded"
                contentWidth="medium"
                sizing="mediumLarge"
                background="fluid"
                cardStyle="subtle-shadow"
                primaryButtonStyle="primary-glow"
                secondaryButtonStyle="glass"
                headingFontWeight="semibold"
            >
                <ReactLenis root>
                    <div id="navbar" data-section="navbar">
                        <NavbarLayoutFloatingInline
                            navItems={[{ name: "Home", id: "/" }, { name: "Shop", id: "/shop" }]}
                            brandName="ProTech"
                            button={{ text: "Cart", onClick: () => setCartOpen(true) }}
                            className="py-4 px-6"
                            navItemClassName="text-foreground hover:text-primary-cta"
                            buttonClassName="bg-primary-cta text-secondary-cta px-6 py-3 rounded-full hover:scale-105 transition-transform duration-300"
                            buttonTextClassName="font-semibold"
                        />
                    </div>
                    <div id="not-found-section" data-section="not-found-section">
                        <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"
                                >
                                    Back to Shop
                                </button>
                            </div>
                        </main>
                    </div>
                    <div id="footer" data-section="footer">
                        <FooterBase
                            columns={[
                                { title: "Services", items: [{ label: "Furnace Repair", href: "#services" }, { label: "AC Replacement", href: "#services" }, { label: "Emergency HVAC", href: "#services" }, { label: "Maintenance Plans", href: "#maintenance-plan" }] },
                                { title: "Company", items: [{ label: "About Us", href: "#about" }, { label: "Why Choose Us", href: "#why-choose-us" }, { label: "Contact", href: "#contact" }, { label: "Reviews", href: "#social-proof" }] },
                                { title: "Legal", items: [{ label: "Privacy Policy", href: "/privacy" }, { label: "Terms of Service", href: "/terms" }] }
                            ]}
                            logoText="ProTech Heating & Cooling"
                            copyrightText="© 2024 ProTech Heating & Cooling Inc. All rights reserved."
                            className="py-12 md:py-16 lg:py-20 bg-foreground text-background-accent"
                            containerClassName="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 grid grid-cols-1 md:grid-cols-4 gap-8"
                            logoTextClassName="text-2xl font-bold text-background mb-6"
                            columnsClassName="grid grid-cols-2 md:grid-cols-3 gap-8 col-span-full md:col-span-3"
                            columnTitleClassName="text-lg font-semibold text-background mb-4"
                            columnItemClassName="text-background/80 hover:text-primary-cta transition-colors duration-200"
                            copyrightContainerClassName="mt-8 md:mt-0 text-background/60 text-sm"
                            copyrightTextClassName="mb-2"
                            privacyButtonClassName="text-primary-cta hover:underline"
                        />
                    </div>
                </ReactLenis>
            </ThemeProvider>
        );
    }

    return (
        <ThemeProvider
            defaultButtonVariant="hover-magnetic"
            defaultTextAnimation="background-highlight"
            borderRadius="rounded"
            contentWidth="medium"
            sizing="mediumLarge"
            background="fluid"
            cardStyle="subtle-shadow"
            primaryButtonStyle="primary-glow"
            secondaryButtonStyle="glass"
            headingFontWeight="semibold"
        >
            <ReactLenis root>
                <div id="navbar" data-section="navbar">
                    <NavbarLayoutFloatingInline
                        navItems={[{ name: "Home", id: "/" }, { name: "Shop", id: "/shop" }]}
                        brandName="ProTech"
                        button={{ text: "Cart", onClick: () => setCartOpen(true) }}
                        className="py-4 px-6"
                        navItemClassName="text-foreground hover:text-primary-cta"
                        buttonClassName="bg-primary-cta text-secondary-cta px-6 py-3 rounded-full hover:scale-105 transition-transform duration-300"
                        buttonTextClassName="font-semibold"
                    />
                </div>
                <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>
                <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">
                    <FooterBase
                        columns={[
                            { title: "Services", items: [{ label: "Furnace Repair", href: "#services" }, { label: "AC Replacement", href: "#services" }, { label: "Emergency HVAC", href: "#services" }, { label: "Maintenance Plans", href: "#maintenance-plan" }] },
                            { title: "Company", items: [{ label: "About Us", href: "#about" }, { label: "Why Choose Us", href: "#why-choose-us" }, { label: "Contact", href: "#contact" }, { label: "Reviews", href: "#social-proof" }] },
                            { title: "Legal", items: [{ label: "Privacy Policy", href: "/privacy" }, { label: "Terms of Service", href: "/terms" }] }
                        ]}
                        logoText="ProTech Heating & Cooling"
                        copyrightText="© 2024 ProTech Heating & Cooling Inc. All rights reserved."
                        className="py-12 md:py-16 lg:py-20 bg-foreground text-background-accent"
                        containerClassName="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 grid grid-cols-1 md:grid-cols-4 gap-8"
                        logoTextClassName="text-2xl font-bold text-background mb-6"
                        columnsClassName="grid grid-cols-2 md:grid-cols-3 gap-8 col-span-full md:col-span-3"
                        columnTitleClassName="text-lg font-semibold text-background mb-4"
                        columnItemClassName="text-background/80 hover:text-primary-cta transition-colors duration-200"
                        copyrightContainerClassName="mt-8 md:mt-0 text-background/60 text-sm"
                        copyrightTextClassName="mb-2"
                        privacyButtonClassName="text-primary-cta hover:underline"
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}
