import {
    LayoutDashboard,
    Users,
    Package,
    Shield,
    Scroll,
    Gift,
    ArrowLeftRight,
    GraduationCap,
    Settings,
    LogOut,
    ChevronLeft,
    ChevronRight,
    Gamepad2,
    Trophy,
    Menu,
    X,
} from "lucide-react";
import { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { cn } from "../lib/utils";
import type { AuthUser } from "../lib/useAuth";

interface NavItem {
    path: string;
    label: string;
    icon: React.ComponentType<{ className?: string }>;
}

const adminNavItems: NavItem[] = [
    { path: "/admin", label: "Dashboard", icon: LayoutDashboard },
    { path: "/admin/users", label: "Users", icon: Users },
    { path: "/admin/items", label: "Items", icon: Package },
    { path: "/admin/classes", label: "Classes", icon: GraduationCap },
    { path: "/admin/quests", label: "Quests", icon: Scroll },
    { path: "/admin/lootdrops", label: "Lootdrops", icon: Gift },
    { path: "/admin/moderation", label: "Moderation", icon: Shield },
    { path: "/admin/transactions", label: "Transactions", icon: ArrowLeftRight },
    { path: "/admin/settings", label: "Settings", icon: Settings },
    { path: "/games", label: "Games", icon: Gamepad2 },
];

const playerNavItems: NavItem[] = [
    { path: "/dashboard", label: "Dashboard", icon: LayoutDashboard },
    { path: "/games", label: "Games", icon: Gamepad2 },
    { path: "/leaderboards", label: "Leaderboards", icon: Trophy },
];

export default function Layout({
    user,
    logout,
    children,
}: {
    user: AuthUser;
    logout: () => Promise<void>;
    children: React.ReactNode;
}) {
    const [collapsed, setCollapsed] = useState(false);
    const [mobileOpen, setMobileOpen] = useState(false);
    const location = useLocation();
    const navigate = useNavigate();

    const navItems = user.role === "admin" ? adminNavItems : playerNavItems;

    const avatarUrl = user.avatar
        ? `https://cdn.discordapp.com/avatars/${user.discordId}/${user.avatar}.png?size=64`
        : null;

    // Close mobile drawer on route change
    useEffect(() => {
        setMobileOpen(false);
    }, [location.pathname]);

    function isActive(path: string): boolean {
        if (path === "/admin" && location.pathname === "/admin") return true;
        if (path === "/dashboard" && location.pathname === "/dashboard") return true;
        if (path !== "/admin" && path !== "/dashboard" && location.pathname.startsWith(path)) return true;
        return false;
    }

    function handleNav(path: string) {
        navigate(path);
        setMobileOpen(false);
    }

    const sidebarContent = (
        <>
            <nav className="flex-1 py-3 px-2 space-y-1 overflow-y-auto">
                {navItems.map(({ path, label, icon: Icon }) => (
                    <button
                        key={path}
                        onClick={() => handleNav(path)}
                        className={cn(
                            "w-full flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",
                            isActive(path)
                                ? "bg-primary/15 text-primary border-l-4 border-primary"
                                : "text-text-tertiary hover:bg-primary/8 hover:text-foreground"
                        )}
                    >
                        <Icon className={cn("w-5 h-5 shrink-0", isActive(path) && "text-primary")} />
                        {(!collapsed || mobileOpen) && <span>{label}</span>}
                    </button>
                ))}
            </nav>

            <div className="border-t border-border p-3 space-y-2">
                {(!collapsed || mobileOpen) && (
                    <div className="flex items-center gap-3 px-2 py-1.5">
                        {avatarUrl ? (
                            <img src={avatarUrl} alt={user.username} className="w-8 h-8 rounded-full" />
                        ) : (
                            <div className="w-8 h-8 rounded-full bg-surface flex items-center justify-center text-xs font-medium">
                                {user.username[0]?.toUpperCase()}
                            </div>
                        )}
                        <div className="flex-1 min-w-0">
                            <div className="text-sm font-medium truncate">{user.username}</div>
                        </div>
                    </div>
                )}
                <div className={cn("flex", collapsed && !mobileOpen ? "flex-col items-center gap-2" : "items-center justify-between px-2")}>
                    <button
                        onClick={logout}
                        className="inline-flex items-center gap-2 rounded-md px-2 py-1.5 text-sm text-text-tertiary hover:text-destructive hover:bg-destructive/10 transition-colors"
                        title="Sign out"
                    >
                        <LogOut className="w-4 h-4" />
                        {(!collapsed || mobileOpen) && <span>Sign out</span>}
                    </button>
                    {/* Collapse toggle only on desktop */}
                    <button
                        onClick={() => setCollapsed((c) => !c)}
                        className="hidden md:block p-1.5 rounded-md text-text-tertiary hover:text-foreground hover:bg-primary/10 transition-colors"
                        title={collapsed ? "Expand sidebar" : "Collapse sidebar"}
                    >
                        {collapsed ? <ChevronRight className="w-4 h-4" /> : <ChevronLeft className="w-4 h-4" />}
                    </button>
                </div>
            </div>
        </>
    );

    return (
        <div className="min-h-screen flex">
            {/* Mobile header bar */}
            <div className="fixed top-0 left-0 right-0 z-40 flex items-center h-14 px-4 bg-background border-b border-border md:hidden">
                <button
                    onClick={() => setMobileOpen(true)}
                    className="p-2 -ml-2 rounded-md text-text-tertiary hover:text-foreground hover:bg-primary/10 transition-colors"
                >
                    <Menu className="w-5 h-5" />
                </button>
                <div className="font-display text-lg font-bold tracking-tight ml-3">Aurora</div>
            </div>

            {/* Mobile overlay */}
            {mobileOpen && (
                <div
                    className="fixed inset-0 z-50 bg-black/50 md:hidden"
                    onClick={() => setMobileOpen(false)}
                />
            )}

            {/* Sidebar - mobile drawer + desktop fixed */}
            <aside
                className={cn(
                    "fixed inset-y-0 left-0 z-50 flex flex-col bg-background border-r border-border transition-all duration-200",
                    // Mobile: off-screen drawer, shown when mobileOpen
                    "w-60 -translate-x-full md:translate-x-0",
                    mobileOpen && "translate-x-0",
                    // Desktop: respect collapsed state
                    !mobileOpen && collapsed && "md:w-16"
                )}
            >
                <div className="flex items-center justify-between h-14 md:h-16 px-4 border-b border-border">
                    <div className="font-display text-xl font-bold tracking-tight">
                        {collapsed && !mobileOpen ? "A" : "Aurora"}
                    </div>
                    {/* Close button on mobile */}
                    <button
                        onClick={() => setMobileOpen(false)}
                        className="p-1.5 rounded-md text-text-tertiary hover:text-foreground md:hidden"
                    >
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {sidebarContent}
            </aside>

            <main className={cn(
                "flex-1 transition-all duration-200",
                // Mobile: no margin, pad for top header bar
                "mt-14 md:mt-0",
                collapsed ? "md:ml-16" : "md:ml-60"
            )}>
                <div className="max-w-[1600px] mx-auto px-4 py-6 md:px-6 md:py-8">
                    {children}
                </div>
            </main>
        </div>
    );
}
