import { ChevronDown, ChevronRight, Package, ClipboardList, ShoppingCart } from "lucide-react";
import { Toaster } from "sonner";
import { useState, useEffect } from "react";
import { Link, usePage } from "@inertiajs/react";
import { cn } from "@/lib/utils";

interface MenuItem {
    id: string;
    label: string;
    icon?: React.ReactNode;
    route?: string;
    children?: MenuItem[];
}

export default function AuthenticatedLayout({ children }: { children: React.ReactNode }) {
    const { url } = usePage();
    const menuItems: MenuItem[] = [
        {
            id: "inventory-management",
            label: "商品與庫存管理",
            icon: <Package className="h-5 w-5" />,
            children: [
                {
                    id: "product-management",
                    label: "商品資料管理",
                    icon: <ClipboardList className="h-4 w-4" />,
                    route: "/products",
                },
                {
                    id: "warehouse-management",
                    label: "倉庫管理",
                    icon: <Package className="h-4 w-4" />,
                    route: "/warehouses",
                },
            ],
        },
        {
            id: "vendor-management",
            label: "廠商管理",
            icon: <Package className="h-5 w-5" />, // Using Package icon for now, can be changed
            children: [
                {
                    id: "vendor-list",
                    label: "廠商資料管理",
                    icon: <ClipboardList className="h-4 w-4" />,
                    route: "/vendors",
                },
            ],
        },
        {
            id: "purchase-management",
            label: "採購管理",
            icon: <ShoppingCart className="h-5 w-5" />,
            children: [
                {
                    id: "purchase-order-list",
                    label: "管理採購單",
                    icon: <ClipboardList className="h-4 w-4" />,
                    route: "/purchase-orders",
                },
            ],
        },
    ];

    // 初始化狀態：優先讀取 localStorage
    const [expandedItems, setExpandedItems] = useState<string[]>(() => {
        try {
            const saved = localStorage.getItem("sidebar-expanded-items");
            if (saved) return JSON.parse(saved);
        } catch (e) {
            console.error("Failed to parse sidebar state", e);
        }

        // 如果沒有存檔，則預設僅展開當前 URL 對應的群組
        const activeItem = menuItems.find(item =>
            item.children?.some(child => child.route && url.startsWith(child.route))
        );
        return activeItem ? [activeItem.id] : ["inventory-management"];
    });

    // 監聽 URL 變化，確保「當前」頁面所屬群組是展開的
    // 但不要影響其他群組的狀態（除非使用者手動切換）
    useEffect(() => {
        const activeItem = menuItems.find(item =>
            item.children?.some(child => child.route && url.startsWith(child.route))
        );

        if (activeItem && !expandedItems.includes(activeItem.id)) {
            setExpandedItems(prev => {
                const next = [...prev, activeItem.id];
                localStorage.setItem("sidebar-expanded-items", JSON.stringify(next));
                return next;
            });
        }
    }, [url]);

    const toggleExpand = (itemId: string) => {
        setExpandedItems((prev) => {
            const next = prev.includes(itemId)
                ? prev.filter((id) => id !== itemId)
                : [...prev, itemId];

            localStorage.setItem("sidebar-expanded-items", JSON.stringify(next));
            return next;
        });
    };

    const renderMenuItem = (item: MenuItem, level: number = 0) => {
        const hasChildren = item.children && item.children.length > 0;
        const isExpanded = expandedItems.includes(item.id);
        const isActive = item.route ? url.startsWith(item.route) : false;

        return (
            <div key={item.id}>
                {hasChildren ? (
                    <button
                        onClick={() => toggleExpand(item.id)}
                        className={cn(
                            "w-full flex items-center gap-3 px-4 py-3 transition-all rounded-md",
                            level === 0 && "hover:bg-background-light",
                            level > 0 && "hover:bg-background-light-grey pl-10"
                        )}
                    >
                        <span className="flex-shrink-0">
                            {isExpanded ? (
                                <ChevronDown className="h-4 w-4 text-[#4a4a4a]" />
                            ) : (
                                <ChevronRight className="h-4 w-4 text-[#4a4a4a]" />
                            )}
                        </span>
                        {item.icon && (
                            <span className="flex-shrink-0 text-[#4a4a4a]">
                                {item.icon}
                            </span>
                        )}
                        <span className="text-[#1a1a1a] transition-colors font-medium">
                            {item.label}
                        </span>
                    </button>
                ) : (
                    <Link
                        href={item.route || "#"}
                        className={cn(
                            "w-full flex items-center gap-3 px-4 py-3 transition-all rounded-md",
                            level === 0 && "hover:bg-background-light",
                            level > 0 && "hover:bg-background-light-grey pl-10",
                            isActive && "bg-[#33bc9a]/20 font-medium"
                        )}
                    >
                        {!hasChildren && level > 0 && <span className="w-4" />}
                        {item.icon && (
                            <span className={cn("flex-shrink-0", isActive ? "text-[#01ab83]" : "text-[#4a4a4a]")}>
                                {item.icon}
                            </span>
                        )}
                        <span className={cn("transition-colors", isActive ? "text-[#01ab83]" : "text-[#1a1a1a]")}>
                            {item.label}
                        </span>
                    </Link>
                )}

                {hasChildren && isExpanded && (
                    <div>
                        {item.children?.map((child) => renderMenuItem(child, level + 1))}
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="flex min-h-screen bg-background">
            {/* Sidebar 底色強制為白色 bg-white */}
            <aside className="w-64 bg-white border-r border-border h-screen flex flex-col fixed left-0 top-0 overflow-y-auto z-50">
                <div className="p-6 border-b border-border mb-4">
                    {/* H2 顏色對應 primary-main (#01ab83) */}
                    <h2 className="text-[#01ab83]">甜點店 ERP 系統</h2>
                </div>
                <nav className="flex-1 py-4 px-2">
                    {menuItems.map((item) => renderMenuItem(item))}
                </nav>
                <div className="p-4 border-t border-border mt-auto">
                    <p className="text-xs text-grey-2">版本 1.0.0</p>
                </div>
            </aside>

            <main className="flex-1 ml-64 overflow-auto min-h-screen bg-background">
                {children}
                <Toaster richColors closeButton position="top-right" />
            </main>
        </div>
    );
}
