import {
    ChevronDown,
    ChevronRight,
    Package,
    ShoppingCart,
    Menu,
    X,
    PanelLeftClose,
    PanelLeftOpen,
    Boxes,
    Warehouse,
    Truck,
    Contact2,
    FileText
} 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 [isCollapsed, setIsCollapsed] = useState(() => {
        if (typeof window !== "undefined") {
            return localStorage.getItem("sidebar-collapsed") === "true";
        }
        return false;
    });
    const [isMobileOpen, setIsMobileOpen] = useState(false);

    const menuItems: MenuItem[] = [
        {
            id: "inventory-management",
            label: "商品與庫存管理",
            icon: <Boxes className="h-5 w-5" />,
            children: [
                {
                    id: "product-management",
                    label: "商品資料管理",
                    icon: <Package className="h-4 w-4" />,
                    route: "/products",
                },
                {
                    id: "warehouse-management",
                    label: "倉庫管理",
                    icon: <Warehouse className="h-4 w-4" />,
                    route: "/warehouses",
                },
            ],
        },
        {
            id: "vendor-management",
            label: "廠商管理",
            icon: <Truck className="h-5 w-5" />,
            children: [
                {
                    id: "vendor-list",
                    label: "廠商資料管理",
                    icon: <Contact2 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: <FileText 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]);

    useEffect(() => {
        localStorage.setItem("sidebar-collapsed", String(isCollapsed));
    }, [isCollapsed]);

    const toggleExpand = (itemId: string) => {
        if (isCollapsed) {
            setIsCollapsed(false);
            if (!expandedItems.includes(itemId)) {
                setExpandedItems(prev => [...prev, itemId]);
            }
            return;
        }

        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} className="mb-1">
                {hasChildren ? (
                    <button
                        onClick={() => toggleExpand(item.id)}
                        className={cn(
                            "w-full flex items-center transition-all rounded-lg group",
                            level === 0 ? "px-3 py-2.5" : "px-3 py-2 pl-10",
                            level === 0 && !isCollapsed && "hover:bg-slate-100",
                            isCollapsed && level === 0 && "justify-center px-0 h-10 w-10 mx-auto hover:bg-slate-100"
                        )}
                        title={isCollapsed ? item.label : ""}
                    >
                        {level === 0 && (
                            <span className={cn(
                                "flex-shrink-0 transition-all",
                                isCollapsed ? "mr-0" : "mr-3 text-slate-500 group-hover:text-slate-900"
                            )}>
                                {item.icon}
                            </span>
                        )}

                        {!isCollapsed && (
                            <>
                                <span className="flex-1 text-left text-base font-medium text-slate-700 group-hover:text-slate-900 truncate">
                                    {item.label}
                                </span>
                                <span className="flex-shrink-0 transition-transform duration-200">
                                    {isExpanded ? (
                                        <ChevronDown className="h-3.5 w-3.5 text-slate-400" />
                                    ) : (
                                        <ChevronRight className="h-3.5 w-3.5 text-slate-400" />
                                    )}
                                </span>
                            </>
                        )}
                    </button>
                ) : (
                    <Link
                        href={item.route || "#"}
                        onClick={() => setIsMobileOpen(false)}
                        className={cn(
                            "w-full flex items-center transition-all rounded-lg group",
                            level === 0 ? "px-3 py-2.5" : "px-3 py-2",
                            level > 0 && !isCollapsed && "pl-11",
                            isActive ? "bg-primary-lightest text-primary-main" : "text-slate-600 hover:bg-slate-100 hover:text-slate-900",
                            isCollapsed && level === 0 && "justify-center px-0 h-10 w-10 mx-auto"
                        )}
                        title={isCollapsed ? item.label : ""}
                    >
                        {item.icon && (
                            <span className={cn(
                                "flex-shrink-0 transition-all",
                                isCollapsed ? "mr-0" : "mr-3",
                                isActive ? "text-primary-main" : "text-slate-500 group-hover:text-slate-900"
                            )}>
                                {item.icon}
                            </span>
                        )}
                        {!isCollapsed && (
                            <span className="text-base font-medium truncate">
                                {item.label}
                            </span>
                        )}
                    </Link>
                )}

                {hasChildren && isExpanded && !isCollapsed && (
                    <div className="mt-1 space-y-1">
                        {item.children?.map((child) => renderMenuItem(child, level + 1))}
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="flex min-h-screen bg-slate-50">
            {/* Mobile Header */}
            <header className="lg:hidden fixed top-0 left-0 right-0 h-16 bg-white border-b border-slate-200 z-[60] flex items-center justify-between px-4">
                <Link href="/" className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-lg bg-primary-main flex items-center justify-center text-white font-bold text-lg">K</div>
                    <span className="font-bold text-slate-900">小小冰室 ERP</span>
                </Link>
                <button
                    onClick={() => setIsMobileOpen(!isMobileOpen)}
                    className="p-2 text-slate-600 hover:bg-slate-100 rounded-lg"
                >
                    {isMobileOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
                </button>
            </header>

            {/* Sidebar Desktop */}
            <aside className={cn(
                "fixed left-0 top-0 bottom-0 bg-white border-r border-slate-200 z-50 transition-all duration-300 ease-in-out hidden lg:flex flex-col",
                isCollapsed ? "w-20" : "w-64"
            )}>
                <div className="h-16 flex items-center justify-between px-6 border-b border-slate-100">
                    {!isCollapsed && (
                        <Link href="/" className="flex items-center gap-2 group">
                            <div className="w-8 h-8 rounded-lg bg-primary-main flex items-center justify-center text-white font-bold text-lg group-hover:scale-110 transition-transform">K</div>
                            <span className="font-extrabold text-[#01ab83] text-lg tracking-tight">小小冰室 ERP</span>
                        </Link>
                    )}
                    {isCollapsed && (
                        <Link href="/" className="w-8 h-8 rounded-lg bg-primary-main flex items-center justify-center text-white font-bold text-lg mx-auto">K</Link>
                    )}
                </div>

                <div className="flex-1 overflow-y-auto overflow-x-hidden p-4 space-y-6">
                    <nav className="space-y-1">
                        {menuItems.map((item) => renderMenuItem(item))}
                    </nav>
                </div>

                <div className="p-4 border-t border-slate-100 flex items-center justify-between">
                    {!isCollapsed && <p className="text-[10px] font-medium text-slate-400 uppercase tracking-wider px-2">Version 1.0.0</p>}
                    <button
                        onClick={() => setIsCollapsed(!isCollapsed)}
                        className={cn(
                            "p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-lg transition-colors",
                            isCollapsed && "mx-auto"
                        )}
                        title={isCollapsed ? "展開側邊欄" : "縮合側邊欄"}
                    >
                        {isCollapsed ? <PanelLeftOpen className="h-5 w-5" /> : <PanelLeftClose className="h-5 w-5" />}
                    </button>
                </div>
            </aside>

            {/* Mobile Sidebar Overlay */}
            {isMobileOpen && (
                <div
                    className="fixed inset-0 bg-slate-900/50 backdrop-blur-sm z-[70] lg:hidden"
                    onClick={() => setIsMobileOpen(false)}
                />
            )}

            {/* Mobile Sidebar Drawer */}
            <aside className={cn(
                "fixed left-0 top-0 bottom-0 w-72 bg-white z-[80] transition-transform duration-300 ease-in-out lg:hidden flex flex-col shadow-2xl",
                isMobileOpen ? "translate-x-0" : "-translate-x-full"
            )}>
                <div className="h-16 flex items-center justify-between px-6 border-b border-slate-100">
                    <Link href="/" className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-lg bg-primary-main flex items-center justify-center text-white font-bold text-lg">K</div>
                        <span className="font-extrabold text-[#01ab83] text-lg">小小冰室 ERP</span>
                    </Link>
                    <button onClick={() => setIsMobileOpen(false)} className="p-2 text-slate-400">
                        <X className="h-5 w-5" />
                    </button>
                </div>
                <div className="flex-1 overflow-y-auto p-4">
                    <nav className="space-y-1">
                        {menuItems.map((item) => renderMenuItem(item))}
                    </nav>
                </div>
            </aside>

            {/* Main Content */}
            <main className={cn(
                "flex-1 transition-all duration-300 min-h-screen overflow-auto",
                "lg:ml-64",
                isCollapsed && "lg:ml-20",
                "pt-16 lg:pt-0" // Mobile header spacing
            )}>
                <div className="relative">
                    {children}
                </div>
                <Toaster richColors closeButton position="top-center" />
            </main>
        </div>
    );
}
