"use client";

import { use, useCallback } from "react";
import { useRouter } from "next/navigation";
import ReactLenis from "lenis/react";
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleFullscreen from '@/components/navbar/NavbarStyleFullscreen/NavbarStyleFullscreen';
import FooterMedia from '@/components/sections/footer/FooterMedia';
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) {
    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="bounce-effect"
                defaultTextAnimation="background-highlight"
                borderRadius="rounded"
                contentWidth="medium"
                sizing="largeSizeMediumTitles"
                background="noise"
                cardStyle="subtle-shadow"
                primaryButtonStyle="double-inset"
                secondaryButtonStyle="glass"
                headingFontWeight="bold"
            >
                <ReactLenis root>
                    <div id="navbar" data-section="navbar">
                    <NavbarStyleFullscreen
                        navItems={[
                            {"name":"Home","id":"/"},
                            {"name":"Services","id":"services"},
                            {"name":"About","id":"about"},
                            {"name":"Testimonials","id":"testimonials"},
                            {"name":"Contact","id":"contact"},
                            {"name":"Shop","id":"/shop"}
                        ]}
                        brandName="JT Roofing"
                        bottomLeftText="Available 24/7 for emergencies"
                        bottomRightText="call@jtroofing.com"
                        button={{ text: "Cart", onClick: () => setCartOpen(true) }}
                    />
                    </div>
                    <main className="min-h-screen flex items-center justify-center pt-20">
                        <p className="text-foreground">Loading product...</p>
                    </main>
                    <div id="footer" data-section="footer">
                    <FooterMedia
                        imageSrc="https://img.b2bpic.net/free-photo/retro-black-alarm-clock-dissolving-into-little-particles-time-can-return-never-wait-anyone-time-management-concept_616485-70.jpg"
                        imageAlt="JT Roofing footer background"
                        logoText="JT Roofing"
                        copyrightText="© 2025 JT Roofing. All rights reserved."
                        columns={[
                            {"title":"Services","items":[{"label":"Emergency Repairs","href":"#services"},{"label":"Roof Replacement","href":"#services"},{"label":"Storm Damage","href":"#services"},{"label":"Inspections","href":"#services"}]},
                            {"title":"Company","items":[{"label":"About Us","href":"#about"},{"label":"Testimonials","href":"#testimonials"},{"label":"FAQs","href":"#faq"},{"label":"Contact","href":"#contact"}]},
                            {"title":"Contact","items":[{"label":"call@jtroofing.com","href":"mailto:call@jtroofing.com"},{"label":"(555) 123-4567","href":"tel:+15551234567"},{"label":"24/7 Emergency Line","href":"tel:+15551234567"}]}
                        ]}
                    />
                    </div>
                </ReactLenis>
            </ThemeProvider>
        );
    }

    return (
        <ThemeProvider
            defaultButtonVariant="bounce-effect"
            defaultTextAnimation="background-highlight"
            borderRadius="rounded"
            contentWidth="medium"
            sizing="largeSizeMediumTitles"
            background="noise"
            cardStyle="subtle-shadow"
            primaryButtonStyle="double-inset"
            secondaryButtonStyle="glass"
            headingFontWeight="bold"
        >
            <ReactLenis root>
                <div id="navbar" data-section="navbar">
                <NavbarStyleFullscreen
                    navItems={[
                        {"name":"Home","id":"/"},
                        {"name":"Services","id":"services"},
                        {"name":"About","id":"about"},
                        {"name":"Testimonials","id":"testimonials"},
                        {"name":"Contact","id":"contact"},
                        {"name":"Shop","id":"/shop"}
                    ]}
                    brandName="JT Roofing"
                    bottomLeftText="Available 24/7 for emergencies"
                    bottomRightText="call@jtroofing.com"
                />
                </div>
                <div id="productCatalog" data-section="productCatalog">
                <ProductCatalog
                    layout="page"
                    products={products}
                    searchValue={search}
                    onSearchChange={setSearch}
                    searchPlaceholder="Search products..."
                    filters={filters}
                    emptyMessage="No products found"
                />
                </div>
                <div id="footer" data-section="footer">
                <FooterMedia
                    imageSrc="https://img.b2bpic.net/free-photo/retro-black-alarm-clock-dissolving-into-little-particles-time-can-return-never-wait-anyone-time-management-concept_616485-70.jpg"
                    imageAlt="JT Roofing footer background"
                    logoText="JT Roofing"
                    copyrightText="© 2025 JT Roofing. All rights reserved."
                    columns={[
                        {"title":"Services","items":[{"label":"Emergency Repairs","href":"#services"},{"label":"Roof Replacement","href":"#services"},{"label":"Storm Damage","href":"#services"},{"label":"Inspections","href":"#services"}]},
                        {"title":"Company","items":[{"label":"About Us","href":"#about"},{"label":"Testimonials","href":"#testimonials"},{"label":"FAQs","href":"#faq"},{"label":"Contact","href":"#contact"}]},
                        {"title":"Contact","items":[{"label":"call@jtroofing.com","href":"mailto:call@jtroofing.com"},{"label":"(555) 123-4567","href":"tel:+15551234567"},{"label":"24/7 Emergency Line","href":"tel:+15551234567"}]}
                    ]}
                />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}