"use client";

import { Suspense, useCallback } from "react";
import ReactLenis from "lenis/react";
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarLayoutFloatingOverlay from '@/components/navbar/NavbarLayoutFloatingOverlay/NavbarLayoutFloatingOverlay';
import FooterMedia from '@/components/sections/footer/FooterMedia';
import ProductCatalog from "@/components/ecommerce/productCatalog/ProductCatalog";
import ProductCart from "@/components/ecommerce/cart/ProductCart";
import { useProductCatalog } from "@/hooks/useProductCatalog";
import { useCart } from "@/hooks/useCart";
import { useCheckout } from "@/hooks/useCheckout";

function ShopPageContent() {
    const {
        products,
        isLoading,
        search,
        setSearch,
        filters,
    } = useProductCatalog({ basePath: "/shop" });

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

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

    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 navItems = [{"name":"Home","id":"/"},{"name":"About Us","id":"about"},{"name":"Menu","id":"products"},{"name":"Testimonials","id":"testimonials"},{"name":"FAQ","id":"faq"},{"name":"Contact","id":"contact"},{"name":"Shop","id":"/shop"}].filter(item => item.id.startsWith('/'));

    if (isLoading) {
        return (
            <ThemeProvider
                defaultButtonVariant="text-stagger"
                defaultTextAnimation="background-highlight"
                borderRadius="soft"
                contentWidth="compact"
                sizing="mediumSizeLargeTitles"
                background="noise"
                cardStyle="solid"
                primaryButtonStyle="primary-glow"
                secondaryButtonStyle="solid"
                headingFontWeight="medium"
            >
                <ReactLenis root>
                    <div id="navbar" data-section="navbar">
                    <NavbarLayoutFloatingOverlay
                        navItems={navItems}
                        brandName="Смачна Випічка"
                        button={{ text: "Cart", onClick: () => setCartOpen(true) }}
                        buttonClassName="min-w-fit px-4 py-2"
                        buttonTextClassName="font-semibold"
                    />
                    </div>
                    <main className="min-h-screen flex items-center justify-center pt-20">
                        <p className="text-foreground">Loading products...</p>
                    </main>
                    <div id="footer" data-section="footer">
                        <FooterMedia
                            logoText="Смачна Випічка"
                            copyrightText="© 2024 Смачна Випічка. All rights reserved."
                            imageSrc="https://img.b2bpic.net/free-photo/top-view-fresh-bread-with-milk-eggs-dark-blue-surface_179666-44600.jpg?_wi=3"
                            imageAlt="Traditional Ukrainian baking tools"
                            columns={[{"title":"Menu","items":[{"label":"Babka","href":"#products"},{"label":"Pampushky","href":"#products"},{"label":"Varenyky","href":"#products"}]},{"title":"Bakery","items":[{"label":"Our Story","href":"#about"},{"label":"FAQ","href":"#faq"},{"label":"Contact","href":"#contact"}]}]}
                            mediaClassName="h-80"
                            mediaWrapperClassName="h-80"
                            logoTextClassName="text-2xl font-bold"
                            copyrightTextClassName="text-sm text-center"
                            columnTitleClassName="font-semibold"
                            columnItemClassName="text-sm"
                            columnsClassName="grid grid-cols-2 lg:grid-cols-3 gap-8"
                            containerClassName="max-w-full px-8"
                        />
                    </div>
                </ReactLenis>
            </ThemeProvider>
        );
    }

    return (
        <ThemeProvider
            defaultButtonVariant="text-stagger"
            defaultTextAnimation="background-highlight"
            borderRadius="soft"
            contentWidth="compact"
            sizing="mediumSizeLargeTitles"
            background="noise"
            cardStyle="solid"
            primaryButtonStyle="primary-glow"
            secondaryButtonStyle="solid"
            headingFontWeight="medium"
        >
            <ReactLenis root>
                <div id="navbar" data-section="navbar">
                <NavbarLayoutFloatingOverlay
                    navItems={navItems}
                    brandName="Смачна Випічка"
                    button={{ text: "Cart", onClick: () => setCartOpen(true) }}
                    buttonClassName="min-w-fit px-4 py-2"
                    buttonTextClassName="font-semibold"
                />
                </div>
                <div id="product-catalog" data-section="product-catalog">
                <ProductCatalog
                    layout="page"
                    products={products}
                    searchValue={search}
                    onSearchChange={setSearch}
                    searchPlaceholder="Search products..."
                    filters={filters}
                    emptyMessage="No products found"
                />
                </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">
                    <FooterMedia
                        logoText="Смачна Випічка"
                        copyrightText="© 2024 Смачна Випічка. All rights reserved."
                        imageSrc="https://img.b2bpic.net/free-photo/top-view-fresh-bread-with-milk-eggs-dark-blue-surface_179666-44600.jpg?_wi=4"
                        imageAlt="Traditional Ukrainian baking tools"
                        columns={[{"title":"Menu","items":[{"label":"Babka","href":"#products"},{"label":"Pampushky","href":"#products"},{"label":"Varenyky","href":"#products"}]},{"title":"Bakery","items":[{"label":"Our Story","href":"#about"},{"label":"FAQ","href":"#faq"},{"label":"Contact","href":"#contact"}]}]}
                        mediaClassName="h-80"
                        mediaWrapperClassName="h-80"
                        logoTextClassName="text-2xl font-bold"
                        copyrightTextClassName="text-sm text-center"
                        columnTitleClassName="font-semibold"
                        columnItemClassName="text-sm"
                        columnsClassName="grid grid-cols-2 lg:grid-cols-3 gap-8"
                        containerClassName="max-w-full px-8"
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}

export default function ShopPage() {
    return (
        <Suspense>
            <ShopPageContent />
        </Suspense>
    );
}
