import * as React from 'react';
import { Link, usePage } from '@inertiajs/react';
import { cn } from '@/lib/utils';
import { useAdminAuth } from '@/features/admin/auth/hooks/useAdminAuth';
import { Button } from '@/components/ui/button';
import { Toaster } from '@/components/ui/sonner';

interface NavItem {
    label: string;
    href: string;
    routeName: string;
    adminOnly?: boolean;
}

const NAV_ITEMS: NavItem[] = [
    {
        label: 'Dashboard',
        href: '/admin/dashboard',
        routeName: 'admin.dashboard',
    },
    {
        label: 'Users',
        href: '/admin/users',
        routeName: 'admin.users.index',
        adminOnly: true,
    },
    {
        label: 'Participants',
        href: '/admin/participants',
        routeName: 'admin.participants.index',
    },
    {
        label: 'Questions',
        href: '/admin/questions',
        routeName: 'admin.questions.index',
        adminOnly: true,
    },
    {
        label: 'Offers',
        href: '/admin/offers',
        routeName: 'admin.offers.index',
        adminOnly: true,
    },
    {
        label: 'Settings',
        href: '/admin/settings',
        routeName: 'admin.settings.index',
        adminOnly: true,
    },
];

/**
 * Shared chrome for every authenticated admin page: collapsible sidebar,
 * top bar with the signed-in admin's name and a logout action, and a
 * role-aware nav that hides admin-only links from viewers.
 */
export default function AdminLayout({
    children,
    title,
}: {
    children: React.ReactNode;
    title: string;
}) {
    const { user, logout } = useAdminAuth();
    const { url } = usePage();
    const [sidebarOpen, setSidebarOpen] = React.useState(false);
    const sidebarRef = React.useRef<HTMLDivElement>(null);

    React.useEffect(() => {
        function handleEscape(e: KeyboardEvent) {
            if (e.key === 'Escape' && sidebarOpen) {
                setSidebarOpen(false);
            }
        }
        document.addEventListener('keydown', handleEscape);
        return () => document.removeEventListener('keydown', handleEscape);
    }, [sidebarOpen]);

    React.useEffect(() => {
        if (sidebarOpen) {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = '';
        }
        return () => {
            document.body.style.overflow = '';
        };
    }, [sidebarOpen]);

    async function handleLogout() {
        await logout();
        // Replace the protected history entry so the browser Back button
        // cannot restore this admin screen after logout.
        window.location.replace('/admin/login');
    }

    const visibleItems = NAV_ITEMS.filter(
        (item) => !item.adminOnly || user?.role === 'admin',
    );

    return (
        <div className="min-h-screen bg-(--color-bg)">
            <Toaster />
            <div className="flex min-h-screen">
                <aside
                    className={cn(
                        'fixed inset-y-0 left-0 z-40 w-64 border-r border-(--color-border) bg-(--color-surface) shadow-lg transition-transform lg:static lg:translate-x-0 lg:shadow-none',
                        sidebarOpen ? 'translate-x-0' : '-translate-x-full',
                    )}
                >
                    <div className="flex h-16 items-center gap-2 border-b border-(--color-border-light) px-6">
                        <span className="text-lg font-semibold tracking-tight text-(--color-accent)">
                            Chowman Admin
                        </span>
                    </div>
                    <nav className="space-y-1 p-4">
                        {visibleItems.map((item) => {
                            const path = url.split('?')[0];
                            const active =
                                path === item.href ||
                                path.startsWith(item.href + '/');
                            return (
                                <Link
                                    key={item.href}
                                    href={item.href}
                                    onClick={() => setSidebarOpen(false)}
                                    aria-current={active ? 'page' : undefined}
                                    className={cn(
                                        'block rounded-lg px-4 py-2.5 text-sm font-medium transition-all duration-200',
                                        active
                                            ? 'bg-(--color-accent)/20 font-semibold text-(--color-accent-light) hover:bg-(--color-accent)/30'
                                            : 'text-(--color-ink-muted) hover:translate-x-0.5 hover:bg-(--color-surface-2) hover:text-(--color-ink)',
                                    )}
                                >
                                    {item.label}
                                </Link>
                            );
                        })}
                    </nav>
                    <div className="mt-auto border-t border-(--color-border-light) p-4 sm:hidden">
                        <p className="text-sm font-medium text-(--color-ink)">
                            {user?.name}
                        </p>
                        <p className="text-xs text-(--color-ink-subtle) capitalize">
                            {user?.role}
                        </p>
                    </div>
                </aside>

                {sidebarOpen && (
                    <div
                        className="fixed inset-0 z-30 bg-black/20 backdrop-blur-sm lg:hidden"
                        onClick={() => setSidebarOpen(false)}
                        aria-hidden="true"
                    />
                )}

                <div className="flex min-w-0 flex-1 flex-col">
                    <header className="flex h-16 items-center justify-between gap-3 border-b border-(--color-border-light) bg-(--color-surface) px-4 shadow-sm lg:px-8">
                        <div className="flex min-w-0 items-center gap-3">
                            <button
                                className="rounded-lg p-2 text-(--color-ink-muted) transition-colors hover:bg-(--color-surface-2) lg:hidden"
                                onClick={() => setSidebarOpen(true)}
                                aria-label="Open navigation"
                            >
                                ☰
                            </button>
                            <h1 className="truncate text-lg font-semibold tracking-tight text-(--color-ink)">
                                {title}
                            </h1>
                        </div>
                        <div className="flex shrink-0 items-center gap-2 sm:gap-4">
                            <div className="hidden text-right sm:block">
                                <p className="text-sm font-medium text-(--color-ink)">
                                    {user?.name}
                                </p>
                                <p className="text-xs text-(--color-ink-subtle) capitalize">
                                    {user?.role}
                                </p>
                            </div>
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={handleLogout}
                            >
                                Log out
                            </Button>
                        </div>
                    </header>

                    <main className="min-w-0 flex-1 p-4 sm:p-6 lg:p-8">{children}</main>
                </div>
            </div>
        </div>
    );
}
