import { router } from '@inertiajs/react';
import {
    ChevronDown,
    BarChart3,
    Bell,
    ClipboardList,
    Code2,
    Download,
    Gamepad2,
    Globe,
    ListOrdered,
    ScrollText,
    Trophy,
    UserRound,
    Users,
    type LucideIcon,
} from 'lucide-react';
import { useEffect, useState, type ReactNode } from 'react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { route } from '@/lib/route';
import { cn } from '@/lib/utils';

export type AppSidebarPage =
    | 'games-result-out'
    | 'games-result-log'
    | 'report'
    | 'domain'
    | 'notification-broadcast'
    | 'team'
    | 'profile'
    | 'code-setup';

type AuthUser = {
    first_name: string;
    last_name: string;
    email: string;
    is_sub_admin?: boolean;
    is_super_admin?: boolean;
} | null;

function SubLink({
    label,
    Icon,
    active,
    onClick,
}: {
    label: string;
    Icon: LucideIcon;
    active: boolean;
    onClick: () => void;
}) {
    return (
        <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={onClick}
            className={cn(
                'h-8 w-full cursor-pointer justify-start gap-2 px-2.5 text-xs font-medium hover:bg-white/10 hover:text-white',
                active ? 'text-white/80' : 'text-white/40',
            )}
        >
            <Icon className="size-3.5 shrink-0" aria-hidden />
            {label}
        </Button>
    );
}

function SubMenu({
    collapsed,
    label,
    Icon,
    open,
    onOpenChange,
    flyoutOpen,
    onFlyoutOpenChange,
    active,
    children,
}: {
    collapsed: boolean;
    label: string;
    Icon: LucideIcon;
    open: boolean;
    onOpenChange: (open: boolean) => void;
    flyoutOpen: boolean;
    onFlyoutOpenChange: (open: boolean) => void;
    active: boolean;
    children: ReactNode;
}) {
    if (collapsed) {
        return (
            <Popover open={flyoutOpen} onOpenChange={onFlyoutOpenChange}>
                <PopoverTrigger
                    render={
                        <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className={cn(
                                'h-8 w-full cursor-pointer justify-center px-0 text-xs font-medium hover:bg-white/10 hover:text-white',
                                'aria-expanded:bg-white/10 aria-expanded:text-white',
                                flyoutOpen || active ? 'text-white/80' : 'text-white/40',
                            )}
                            aria-label={label}
                        />
                    }
                >
                    <Icon className="size-3.5 shrink-0" aria-hidden />
                </PopoverTrigger>
                <PopoverContent
                    side="right"
                    align="start"
                    sideOffset={10}
                    className="w-48 gap-0 border-0 bg-[oklch(0.205_0_0)] p-1.5 text-white shadow-lg ring-1 ring-white/10"
                >
                    <p className="px-2.5 pb-1 pt-1.5 text-[11px] font-medium tracking-wide text-white/40">
                        {label}
                    </p>
                    {children}
                </PopoverContent>
            </Popover>
        );
    }

    return (
        <>
            <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => onOpenChange(!open)}
                className={cn(
                    'h-8 w-full cursor-pointer justify-start gap-2 px-2.5 text-xs font-medium hover:bg-white/10 hover:text-white',
                    'aria-expanded:bg-white/10 aria-expanded:text-white',
                    open || active ? 'text-white/80' : 'text-white/40',
                )}
                aria-expanded={open}
                aria-label={label}
            >
                <Icon className="size-3.5 shrink-0" aria-hidden />
                <span className="flex-1 text-left">{label}</span>
                <ChevronDown
                    className={cn(
                        'size-3.5 shrink-0 transition-transform',
                        open && 'rotate-180',
                    )}
                    aria-hidden
                />
            </Button>
            {open && (
                <div className="mt-0.5 ml-2 border-l border-white/10 pl-2">{children}</div>
            )}
        </>
    );
}

export function AppSidebar({
    auth,
    collapsed,
    active,
    mobileOpen = false,
    onMobileClose,
}: {
    auth: { user: AuthUser };
    collapsed: boolean;
    active: AppSidebarPage;
    mobileOpen?: boolean;
    onMobileClose?: () => void;
}) {
    const gamesActive = active === 'games-result-out' || active === 'games-result-log';
    const [gamesOpen, setGamesOpen] = useState(gamesActive);
    const [gamesFlyoutOpen, setGamesFlyoutOpen] = useState(false);
    const [codeOpen, setCodeOpen] = useState(active === 'code-setup');
    const [codeFlyoutOpen, setCodeFlyoutOpen] = useState(false);
    const [isDesktop, setIsDesktop] = useState(
        () => typeof window !== 'undefined' && window.matchMedia('(min-width: 1024px)').matches,
    );

    useEffect(() => {
        const mq = window.matchMedia('(min-width: 1024px)');
        const sync = () => setIsDesktop(mq.matches);
        sync();
        mq.addEventListener('change', sync);
        return () => mq.removeEventListener('change', sync);
    }, []);

    // Mobile drawer always shows expanded labels; desktop uses collapsed width/icons.
    const navCollapsed = isDesktop && collapsed;

    function navigate(to: () => void) {
        onMobileClose?.();
        to();
    }

    const topItems = [
        {
            key: 'report' as const,
            label: 'Report',
            Icon: BarChart3,
            onClick: () => navigate(() => router.get(route('report'))),
        },
        {
            key: 'domain' as const,
            label: 'Domain',
            Icon: Globe,
            onClick: () => navigate(() => router.get(route('domain'))),
        },
        {
            key: 'notification-broadcast' as const,
            label: 'Notification Broadcast',
            Icon: Bell,
            onClick: () => navigate(() => router.get(route('notification-broadcast'))),
        },
        {
            key: 'team' as const,
            label: 'Sub Admin',
            Icon: Users,
            onClick: () => navigate(() => router.get(route('team'))),
        },
    ];

    return (
        <>
            <button
                type="button"
                aria-label="Close sidebar"
                className={cn(
                    'fixed inset-0 z-40 bg-black/40 transition-opacity lg:hidden',
                    mobileOpen ? 'opacity-100' : 'pointer-events-none opacity-0',
                )}
                onClick={onMobileClose}
            />

            <aside
                className={cn(
                    'flex shrink-0 flex-col rounded-2xl border border-border bg-[oklch(0.205_0_0)] text-white/90 shadow-sm',
                    'fixed inset-y-3 left-3 z-50 w-56 transition-transform duration-200',
                    'lg:static lg:z-auto lg:translate-x-0',
                    mobileOpen
                        ? 'translate-x-0'
                        : 'pointer-events-none -translate-x-[calc(100%+0.75rem)] lg:pointer-events-auto',
                    collapsed ? 'lg:w-14' : 'lg:w-56',
                )}
            >
                <div
                    className={cn(
                        'flex h-12 shrink-0 items-center gap-2',
                        navCollapsed ? 'justify-center px-0' : 'px-4',
                    )}
                >
                    <div className="flex size-6 shrink-0 items-center justify-center rounded-full bg-white/15">
                        <Gamepad2 className="size-3.5" aria-hidden />
                    </div>
                    {!navCollapsed && (
                        <span className="font-heading text-sm font-semibold tracking-tight">
                            SuperGame
                        </span>
                    )}
                </div>

                <nav className="flex flex-col gap-0.5 p-2">
                    {!navCollapsed && (
                        <p className="px-2.5 pb-1 pt-2 text-[11px] font-medium tracking-wide text-white/40">
                            Pages
                        </p>
                    )}

                    <div className="mt-0.5">
                        <SubMenu
                            collapsed={navCollapsed}
                            label="Games"
                            Icon={Trophy}
                            open={gamesOpen}
                            onOpenChange={setGamesOpen}
                            flyoutOpen={gamesFlyoutOpen}
                            onFlyoutOpenChange={setGamesFlyoutOpen}
                            active={gamesActive}
                        >
                            <SubLink
                                label="Game Result Out"
                                Icon={ClipboardList}
                                active={active === 'games-result-out'}
                                onClick={() => navigate(() => router.get(route('games')))}
                            />
                            <SubLink
                                label="Game Result Log"
                                Icon={ScrollText}
                                active={active === 'games-result-log'}
                                onClick={() =>
                                    navigate(() => router.get(route('games.result-log')))
                                }
                            />
                        </SubMenu>
                    </div>

                    {topItems.map(({ key, label, Icon, onClick }) => (
                        <Button
                            key={key}
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={onClick}
                            className={cn(
                                'h-8 w-full cursor-pointer gap-2 text-xs font-medium hover:bg-white/10 hover:text-white',
                                active === key ? 'text-white/80' : 'text-white/40',
                                navCollapsed ? 'justify-center px-0' : 'justify-start px-2.5',
                            )}
                        >
                            <Icon className="size-3.5 shrink-0" aria-hidden />
                            {!navCollapsed && label}
                        </Button>
                    ))}

                    <div className="mt-0.5">
                        <SubMenu
                            collapsed={navCollapsed}
                            label="Code"
                            Icon={Code2}
                            open={codeOpen}
                            onOpenChange={setCodeOpen}
                            flyoutOpen={codeFlyoutOpen}
                            onFlyoutOpenChange={setCodeFlyoutOpen}
                            active={active === 'code-setup'}
                        >
                            <SubLink
                                label="Download code"
                                Icon={Download}
                                active={false}
                                onClick={() => {
                                    onMobileClose?.();
                                    window.location.href = route('code.download');
                                }}
                            />
                            <SubLink
                                label="Setup steps"
                                Icon={ListOrdered}
                                active={active === 'code-setup'}
                                onClick={() => navigate(() => router.get(route('code.setup')))}
                            />
                        </SubMenu>
                    </div>

                    <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => navigate(() => router.get(route('profile')))}
                        className={cn(
                            'mt-0.5 h-8 w-full cursor-pointer gap-2 text-xs font-medium hover:bg-white/10 hover:text-white',
                            active === 'profile' ? 'text-white/80' : 'text-white/40',
                            navCollapsed ? 'justify-center px-0' : 'justify-start px-2.5',
                        )}
                    >
                        <UserRound className="size-3.5 shrink-0" aria-hidden />
                        {!navCollapsed && 'Profile'}
                    </Button>
                </nav>

                <div className="mt-auto p-2">
                    <div
                        className={cn(
                            'flex items-center gap-2 rounded-lg px-2.5 py-2',
                            navCollapsed && 'justify-center px-0',
                        )}
                    >
                        <div className="flex size-6 shrink-0 items-center justify-center rounded-full bg-white/15 text-[11px] font-semibold">
                            {auth.user?.first_name?.[0] ?? 'U'}
                        </div>
                        {!navCollapsed && (
                            <div className="min-w-0">
                                <p className="truncate text-xs font-medium text-white">
                                    {auth.user
                                        ? `${auth.user.first_name} ${auth.user.last_name}`
                                        : 'User'}
                                </p>
                                <p className="truncate text-[11px] text-white/40">
                                    {auth.user?.email}
                                </p>
                            </div>
                        )}
                    </div>
                </div>
            </aside>
        </>
    );
}
