import { Link, router, usePage } from '@inertiajs/react';
import {
    LayoutDashboard,
    Users,
    Building2,
    FileText,
    Calendar,
    BookOpen,
    Video,
    Globe,
    UserCheck,
    Award,
    Layers,
    Handshake,
    Clock,
    Settings,
    ShieldCheck,
    Menu,
    X,
    Sun,
    Moon,
    LogOut,
} from 'lucide-react';
import { type PropsWithChildren, useState } from 'react';
import { Toaster } from 'sonner';
import { useAppearance } from '@/hooks/use-appearance';
import { Button } from '@/components/ui/button';
import { FlashMessage } from '@/components/admin/flash-message';

const navGroups = [
    {
        label: 'Overview',
        items: [
            { href: '/admin', label: 'Dashboard', icon: LayoutDashboard },
        ],
    },
    {
        label: 'Members',
        items: [
            { href: '/admin/institutions', label: 'Institutions', icon: Building2 },
            { href: '/admin/subscriptions', label: 'Subscriptions', icon: UserCheck },
            { href: '/admin/tiers', label: 'Membership Tiers', icon: Award },
            { href: '/admin/countries', label: 'Countries', icon: Globe },
            { href: '/admin/divisions', label: 'Divisions', icon: Layers },
        ],
    },
    {
        label: 'Content',
        items: [
            { href: '/admin/posts', label: 'News', icon: FileText },
            { href: '/admin/events', label: 'Events', icon: Calendar },
            { href: '/admin/publications', label: 'Publications', icon: BookOpen },
            { href: '/admin/videos', label: 'Videos', icon: Video },
            { href: '/admin/themes', label: 'Themes', icon: Layers },
            { href: '/admin/summer-schools', label: 'Summer Schools', icon: Sun },
            { href: '/admin/research-initiatives', label: 'Research Spin-offs', icon: BookOpen },
            { href: '/admin/pages', label: 'Pages', icon: Globe },
        ],
    },
    {
        label: 'Organisation',
        items: [
            { href: '/admin/board', label: 'Board', icon: Award },
            { href: '/admin/partners', label: 'Partners', icon: Handshake },
            { href: '/admin/timeline', label: 'Timeline', icon: Clock },
        ],
    },
    {
        label: 'Inbox',
        items: [
            { href: '/admin/messages', label: 'Messages', icon: ShieldCheck },
            { href: '/admin/newsletter', label: 'Newsletter', icon: FileText },
        ],
    },
    {
        label: 'System',
        items: [
            { href: '/admin/settings', label: 'Settings', icon: Settings },
            { href: '/admin/users', label: 'Users', icon: Users },
        ],
    },
];

export default function AdminLayout({ children }: PropsWithChildren) {
    const { auth } = usePage().props;
    const user = (auth as { user: { name: string; email: string } }).user;
    const { appearance, updateAppearance } = useAppearance();
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const { url: currentUrl } = usePage();
    const currentPath = currentUrl.split('?')[0];

    const isActive = (href: string) => {
        if (href === '/admin') return currentPath === '/admin';
        return currentPath.startsWith(href);
    };

    const toggleTheme = () => {
        updateAppearance(appearance === 'dark' ? 'light' : 'dark');
    };

    return (
        <div className="flex min-h-screen bg-background">
            {/* Sidebar */}
            <aside
                className={`fixed inset-y-0 left-0 z-40 flex w-64 flex-col bg-sidebar text-sidebar-foreground transition-transform duration-300 lg:translate-x-0 ${
                    sidebarOpen ? 'translate-x-0' : '-translate-x-full'
                }`}
            >
                {/* Logo */}
                <div className="flex h-16 items-center gap-3 border-b border-sidebar-border px-6">
                    <div className="flex h-8 w-8 items-center justify-center rounded bg-sidebar-primary text-sidebar-primary-foreground">
                        <span className="text-xs font-bold">A</span>
                    </div>
                    <div>
                        <p className="text-xs font-bold uppercase tracking-widest text-sidebar-foreground">ABEC Africa</p>
                        <p className="text-[10px] text-sidebar-foreground/40">Admin Panel</p>
                    </div>
                </div>

                {/* Nav */}
                <nav className="flex-1 overflow-y-auto px-3 py-4">
                    {navGroups.map((group) => (
                        <div key={group.label} className="mb-6">
                            <p className="mb-2 px-3 text-[10px] font-semibold uppercase tracking-widest text-sidebar-foreground/40">
                                {group.label}
                            </p>
                            <ul className="space-y-0.5">
                                {group.items.map((item) => (
                                    <li key={item.href}>
                                        <Link
                                            href={item.href}
                                            onClick={() => setSidebarOpen(false)}
                                            className={`flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors ${
                                                isActive(item.href)
                                                    ? 'bg-sidebar-accent text-sidebar-primary font-medium'
                                                    : 'text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground'
                                            }`}
                                        >
                                            <item.icon className="h-4 w-4 shrink-0" />
                                            {item.label}
                                        </Link>
                                    </li>
                                ))}
                            </ul>
                        </div>
                    ))}
                </nav>

                {/* User */}
                <div className="border-t border-sidebar-border p-4">
                    <div className="flex items-center justify-between">
                        <div className="min-w-0">
                            <p className="truncate text-sm font-medium text-sidebar-foreground">{user?.name}</p>
                            <p className="truncate text-xs text-sidebar-foreground/50">{user?.email}</p>
                        </div>
                        <button
                            onClick={() => router.post('/logout')}
                            className="shrink-0 rounded-md p-2 text-sidebar-foreground/50 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
                            title="Logout"
                        >
                            <LogOut className="h-4 w-4" />
                        </button>
                    </div>
                </div>
            </aside>

            {/* Mobile overlay */}
            {sidebarOpen && (
                <div
                    className="fixed inset-0 z-30 bg-black/50 lg:hidden"
                    onClick={() => setSidebarOpen(false)}
                />
            )}

            {/* Main */}
            <div className="flex flex-1 flex-col lg:pl-64">
                <header className="sticky top-0 z-20 flex h-16 items-center justify-between border-b border-border bg-background/95 px-6 backdrop-blur-sm">
                    <button
                        onClick={() => setSidebarOpen(!sidebarOpen)}
                        className="rounded-md p-2 text-foreground/60 hover:bg-muted lg:hidden"
                    >
                        {sidebarOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
                    </button>

                    <div className="hidden lg:block" />

                    <div className="flex items-center gap-2">
                        <Button variant="ghost" size="icon" onClick={toggleTheme} className="h-9 w-9" title="Toggle theme">
                            {appearance === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
                        </Button>
                        <a
                            href="/"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-xs text-muted-foreground transition-colors hover:text-foreground"
                        >
                            View Site
                        </a>
                    </div>
                </header>

                <main className="flex-1 space-y-6 p-6 lg:p-8">
                    <FlashMessage />
                    {children}
                </main>
            </div>

            <Toaster position="top-right" richColors closeButton />
        </div>
    );
}
