import React, { useEffect, useMemo, useRef, useState } from "react";
import { Link } from "@inertiajs/react";
import {
    LayoutDashboard,
    ShoppingCart,
    Package,
    CreditCard,
    Search,
    ChevronRight,
    Menu,
    Home,
    Sun,
    User,
    LogOut,
    Plus,
    ShoppingBag,
    Wallet,
    BadgeDollarSign,
    Receipt,
    BadgeHelp,
    X,
    Store,
    MessageCircle,
    Clapperboard,
    RotateCcw,
    Bell,
    History,
    HandCoins,
} from "lucide-react";

const menuData = [
    {
        title: "Dashboard",
        icon: LayoutDashboard,
        href: "/seller/dashboard",
    },
    {
        title: "Order",
        icon: ShoppingCart,
        children: [{ label: "Orders", icon: ShoppingBag, href: "/seller/orders" }],
    },
    {
        title: "Product",
        icon: Package,
        children: [
            { label: "Products", icon: Package, href: "/seller/products" },
            { label: "Add Product", icon: Plus, href: "/seller/products/create" },
            { label: "Product Review", icon: BadgeHelp, href: "/seller/reviews" },
            { label: "Stock Management", icon: Plus, href: "/seller/stock-management" },
        ],
    },
    {
        title: "Withdraws",
        icon: Wallet,
        children: [
            { label: "Withdraw Request", icon: HandCoins, href: "/seller/withdraw" },
            { label: "Withdraw History", icon: History, href: "/seller/withdraw/history" },
        ],
    },
    {
        title: "My Shop",
        icon: Store,
        href: "/seller/shop",
    },
    {
        title: "Chat",
        icon: MessageCircle,
        href: "/seller/chat",
    },
    {
        title: "Reels",
        icon: Clapperboard,
        href: "/seller/reels",
    },
    {
        title: "Returns",
        icon: RotateCcw,
        href: "/seller/returns",
    },
    {
        title: "Notice",
        icon: Bell,
        href: "/seller/notice",
    },
    {
        title: "Data & Advisor",
        icon: CreditCard,
        children: [
            {
                label: "Earning Report",
                icon: BadgeDollarSign,
                href: "/seller/reports/earnings",
            },
            {
                label: "Order Report",
                icon: Receipt,
                href: "/seller/reports/orders",
            },
        ],
    },
];

function getDefaultOpenMenus(pathname) {
    const menus = {};

    menuData.forEach((item) => {
        if (item.children?.length) {
            menus[item.title] = item.children.some((child) => child.href === pathname);
        }
    });

    return menus;
}

function SellerPageLoader() {
    return (
        <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-white">
            <div className="flex flex-col items-center justify-center">
                <div className="mb-4 flex h-24 w-24 items-center justify-center rounded-2xl bg-orange-50 shadow-lg">
                    <img
                        src="/frontend/logo.png"
                        alt="Loading"
                        className="h-14 w-14 animate-spin object-contain"
                    />
                </div>

                <h2 className="text-lg font-semibold text-orange-600">Loading...</h2>

                <div className="mt-4 h-1.5 w-40 overflow-hidden rounded-full bg-orange-100">
                    <div className="h-full w-full animate-pulse rounded-full bg-orange-500" />
                </div>
            </div>
        </div>
    );
}

function SidebarItem({
    item,
    openMenus,
    toggleMenu,
    sidebarOpen,
    pathname,
    isMobile,
    onNavigate,
}) {
    const Icon = item.icon;
    const hasChildren = !!item.children?.length;
    const isOpen = !!openMenus[item.title];
    const contentRef = useRef(null);
    const [contentHeight, setContentHeight] = useState(0);

    const isParentActive = item.href === pathname;
    const hasActiveChild = item.children?.some((child) => child.href === pathname);
    const isActive = isParentActive || hasActiveChild;

    useEffect(() => {
        if (contentRef.current) {
            setContentHeight(contentRef.current.scrollHeight);
        }
    }, [isOpen, sidebarOpen, item.children]);

    if (!hasChildren && item.href) {
        return (
            <div className="mb-1.5">
                <Link
                    href={item.href}
                    onClick={() => {
                        if (isMobile) onNavigate?.();
                    }}
                    className={`group flex w-full items-center rounded-xl py-2.5 text-sm transition-all duration-300 ease-out ${
                        sidebarOpen ? "justify-between px-3" : "justify-center px-2"
                    } ${
                        isActive
                            ? "bg-orange-50 text-orange-600 shadow-[0_1px_2px_rgba(0,0,0,0.05)]"
                            : "text-gray-800 hover:bg-gray-100"
                    }`}
                >
                    <span className="flex items-center gap-3 font-medium">
                        <Icon
                            className={`h-4 w-4 shrink-0 transition-transform duration-300 ease-out ${
                                isActive ? "scale-110" : "group-hover:scale-110"
                            }`}
                            strokeWidth={1.9}
                        />
                        {sidebarOpen && <span>{item.title}</span>}
                    </span>
                </Link>
            </div>
        );
    }

    return (
        <div className="mb-1.5">
            <button
                type="button"
                onClick={() => hasChildren && toggleMenu(item.title)}
                className={`group flex w-full items-center rounded-xl py-2.5 text-sm transition-all duration-300 ease-out ${
                    sidebarOpen ? "justify-between px-3" : "justify-center px-2"
                } ${
                    isActive
                        ? "bg-orange-50 text-orange-600 shadow-[0_1px_2px_rgba(0,0,0,0.05)]"
                        : "text-gray-800 hover:bg-gray-100"
                }`}
            >
                <span className="flex items-center gap-3 font-medium">
                    <Icon
                        className={`h-4 w-4 shrink-0 transition-transform duration-300 ease-out ${
                            isActive ? "scale-110" : "group-hover:scale-110"
                        }`}
                        strokeWidth={1.9}
                    />
                    {sidebarOpen && <span>{item.title}</span>}
                </span>

                {sidebarOpen && hasChildren && (
                    <span
                        className="transition-transform duration-300 ease-out"
                        style={{ transform: isOpen ? "rotate(90deg)" : "rotate(0deg)" }}
                    >
                        <ChevronRight className="h-4 w-4" />
                    </span>
                )}
            </button>

            {sidebarOpen && hasChildren && (
                <div
                    className="overflow-hidden transition-all duration-300 ease-out"
                    style={{
                        maxHeight: isOpen ? `${contentHeight}px` : "0px",
                        opacity: isOpen ? 1 : 0,
                        transform: isOpen ? "translateY(0px)" : "translateY(-8px)",
                    }}
                >
                    <div
                        ref={contentRef}
                        className="ml-2 mt-1 space-y-1 border-l border-gray-200 pl-4 pb-1 pt-1"
                    >
                        {item.children.map((child, index) => {
                            const ChildIcon = child.icon;
                            const childActive = pathname === child.href;

                            return (
                                <Link
                                    key={child.label}
                                    href={child.href}
                                    onClick={() => {
                                        if (isMobile) onNavigate?.();
                                    }}
                                    className={`flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-sm transition-all duration-200 ease-out hover:translate-x-1 ${
                                        childActive
                                            ? "bg-orange-50 font-medium text-orange-600"
                                            : "text-gray-700 hover:bg-gray-100"
                                    }`}
                                    style={{
                                        transitionDelay: isOpen ? `${index * 35}ms` : "0ms",
                                    }}
                                >
                                    <ChildIcon className="h-3.5 w-3.5 shrink-0" strokeWidth={1.8} />
                                    <span>{child.label}</span>
                                </Link>
                            );
                        })}
                    </div>
                </div>
            )}
        </div>
    );
}

export default function SellerLayout({
    children,
    pageTitle = "Dashboard",
    pageIcon: PageIcon = Home,
}) {
    const pathname =
        typeof window !== "undefined" ? window.location.pathname : "";

    const derivedOpenMenus = useMemo(() => getDefaultOpenMenus(pathname), [pathname]);

    const [openMenus, setOpenMenus] = useState(derivedOpenMenus);
    const [profileOpen, setProfileOpen] = useState(false);
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [isMobile, setIsMobile] = useState(false);
    const [loggingOut, setLoggingOut] = useState(false);
    const [pageLoading, setPageLoading] = useState(true);

    useEffect(() => {
        setOpenMenus((prev) => ({
            ...prev,
            ...derivedOpenMenus,
        }));
    }, [derivedOpenMenus]);

    useEffect(() => {
        let timer;

        const hideLoader = () => {
            timer = setTimeout(() => {
                setPageLoading(false);
            }, 800);
        };

        if (document.readyState === "complete") {
            hideLoader();
        } else {
            window.addEventListener("load", hideLoader);
        }

        return () => {
            window.removeEventListener("load", hideLoader);
            if (timer) clearTimeout(timer);
        };
    }, []);

    const toggleMenu = (title) => {
        setOpenMenus((prev) => ({
            ...prev,
            [title]: !prev[title],
        }));
    };

    const handleLogout = async () => {
        if (loggingOut) return;

        try {
            setLoggingOut(true);

            const token = document
                .querySelector('meta[name="csrf-token"]')
                ?.getAttribute("content");

            const response = await fetch("/logout", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": token || "",
                    Accept: "application/json",
                },
                credentials: "same-origin",
            });

            if (!response.ok) {
                throw new Error("Logout failed");
            }

            window.location.href = "/";
        } catch (error) {
            console.error(error);
            setLoggingOut(false);
            alert("Logout failed. Please try again.");
        }
    };

    useEffect(() => {
        const checkScreen = () => {
            const mobile = window.innerWidth < 768;
            setIsMobile(mobile);
            setSidebarOpen(mobile ? false : true);
        };

        checkScreen();
        window.addEventListener("resize", checkScreen);
        return () => window.removeEventListener("resize", checkScreen);
    }, []);

    useEffect(() => {
        const handleClickOutside = () => setProfileOpen(false);

        if (profileOpen) {
            window.addEventListener("click", handleClickOutside);
        }

        return () => window.removeEventListener("click", handleClickOutside);
    }, [profileOpen]);

    const handleMobileNavigate = () => {
        if (isMobile) {
            setSidebarOpen(false);
        }
    };

    const sidebarWidth = isMobile ? "0px" : sidebarOpen ? "235px" : "76px";

    return (
        <>
            {pageLoading && <SellerPageLoader />}

            <div className="min-h-screen bg-[#f3f4f6] text-gray-900">
                {isMobile && sidebarOpen && (
                    <div
                        onClick={() => setSidebarOpen(false)}
                        className="fixed inset-0 z-40 bg-black/30 backdrop-blur-[1px] transition-opacity duration-300"
                    />
                )}

                <aside
                    className={`fixed left-0 top-0 z-50 h-screen overflow-y-auto border-r border-gray-200 bg-[#f5f5f5] shadow-[0_1px_2px_rgba(0,0,0,0.05)] transition-all duration-300 ease-out ${
                        isMobile
                            ? sidebarOpen
                                ? "w-[260px] translate-x-0"
                                : "w-[260px] -translate-x-full"
                            : sidebarOpen
                            ? "w-[235px] translate-x-0"
                            : "w-[76px] translate-x-0"
                    }`}
                >
                    <div
                        className={`flex items-center px-4 py-4 ${
                            sidebarOpen ? "justify-between" : "justify-center"
                        }`}
                    >
                        <div className={`flex items-center ${sidebarOpen ? "gap-3" : "justify-center"}`}>
                            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-white p-1 shadow-[0_1px_2px_rgba(0,0,0,0.05)]">
                                <img
                                    src="/frontend/logo.png"
                                    alt="Logo"
                                    className="h-full w-full object-contain"
                                />
                            </div>

                            {sidebarOpen && (
                                <h1 className="text-[18px] font-bold text-orange-600">
                                   Seller Center
                                </h1>
                            )}
                        </div>

                        {isMobile && sidebarOpen && (
                            <button
                                onClick={() => setSidebarOpen(false)}
                                className="rounded-lg p-2 transition-colors duration-200 hover:bg-gray-100"
                            >
                                <X className="h-5 w-5" />
                            </button>
                        )}
                    </div>

                    {sidebarOpen && (
                        <div className="mt-3 px-4 pb-4">
                            <div className="relative">
                                <Search className="pointer-events-none absolute left-3 top-1/2 mt-2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                                <input
                                    type="text"
                                    placeholder="Search..."
                                    className="h-11 w-full rounded-xl border border-gray-200 bg-white pl-10 pr-4 text-sm shadow-[0_1px_2px_rgba(0,0,0,0.05)] outline-none transition-all duration-300 focus:border-orange-400"
                                />
                            </div>
                        </div>
                    )}

                    <nav className="px-2 pb-8">
                        {menuData.map((item) => (
                            <SidebarItem
                                key={item.title}
                                item={item}
                                openMenus={openMenus}
                                toggleMenu={toggleMenu}
                                sidebarOpen={sidebarOpen}
                                pathname={pathname}
                                isMobile={isMobile}
                                onNavigate={handleMobileNavigate}
                            />
                        ))}
                    </nav>
                </aside>

                <header
                    className="fixed top-0 z-30 flex h-16 items-center justify-between border-b border-gray-200 bg-[#fafafa] px-4 shadow-[0_1px_2px_rgba(0,0,0,0.05)] transition-all duration-300 ease-out"
                    style={{
                        left: isMobile ? "0px" : sidebarWidth,
                        width: isMobile ? "100%" : `calc(100% - ${sidebarWidth})`,
                    }}
                >
                    <div className="flex items-center gap-3 sm:gap-4">
                        <button
                            onClick={() => setSidebarOpen((v) => !v)}
                            className="rounded-lg p-2 transition-all duration-200 hover:bg-gray-100"
                        >
                            <Menu className="h-5 w-5" />
                        </button>

                        <div className="flex items-center gap-2 text-sm font-semibold sm:gap-3">
                            <PageIcon className="h-4 w-4" />
                            <span>{pageTitle}</span>
                        </div>
                    </div>

                    <div className="relative flex items-center gap-2 sm:gap-3">
                        <button className="rounded-xl border border-gray-200 bg-white p-2 shadow-[0_1px_2px_rgba(0,0,0,0.05)] transition-all duration-200 hover:bg-gray-50">
                            <Sun className="h-4 w-4" />
                        </button>

                        <button
                            onClick={(e) => {
                                e.stopPropagation();
                                setProfileOpen((v) => !v);
                            }}
                            className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-200 transition-all duration-200 hover:bg-gray-300"
                        >
                            <User className="h-4 w-4 text-gray-600" />
                        </button>

                        <div
                            onClick={(e) => e.stopPropagation()}
                            className="absolute right-0 top-12 z-20 w-36 overflow-hidden rounded-xl border border-gray-200 bg-white shadow-[0_10px_30px_rgba(0,0,0,0.08)] transition-all duration-200 ease-out"
                            style={{
                                opacity: profileOpen ? 1 : 0,
                                transform: profileOpen
                                    ? "translateY(0px) scale(1)"
                                    : "translateY(-8px) scale(0.98)",
                                pointerEvents: profileOpen ? "auto" : "none",
                            }}
                        >
                            <div className="border-b border-gray-100 px-4 py-3 text-sm font-semibold">
                                Seller
                            </div>

                            <Link
                                href="/seller/profile"
                                className="flex w-full items-center gap-2 px-4 py-3 text-sm transition-colors duration-200 hover:bg-gray-50"
                            >
                                <User className="h-4 w-4 text-gray-500" />
                                Profile
                            </Link>

                            <button
                                onClick={handleLogout}
                                disabled={loggingOut}
                                className="flex w-full items-center gap-2 px-4 py-3 text-sm transition-colors duration-200 hover:bg-gray-50 disabled:opacity-60"
                            >
                                <LogOut className="h-4 w-4 text-gray-500" />
                                {loggingOut ? "Logging out..." : "Log Out"}
                            </button>
                        </div>
                    </div>
                </header>

                <main
                    className="min-h-screen p-4 pt-24 transition-all duration-300 ease-out sm:p-6 sm:pt-24"
                    style={{ marginLeft: isMobile ? "0px" : sidebarWidth }}
                >
                    {children}
                </main>
            </div>
        </>
    );
}