import { Link, usePage } from '@inertiajs/react'
import { motion } from 'framer-motion'
import { useState } from 'react'
import {
    LayoutDashboard, FileText, Package, FolderTree, Search, Settings,
    Users, CreditCard, BarChart3, ChevronLeft, ChevronRight, Target, LogOut, Globe, Bell,
    ShoppingBag, RefreshCw, Store, AlertTriangle, Shield, Activity, Mail, Radio, MessageSquare
} from 'lucide-react'
import { CommandPalette } from '@/Components/ui/CommandPalette'
import { ThemeToggle } from '@/Hooks/useTheme'

const commandItems = [
    { id: 'dashboard', label: 'Dashboard', description: 'Admin overview', icon: <LayoutDashboard className="w-4 h-4" />, href: '/admin', category: 'Navigation' },
    { id: 'homepage', label: 'Homepage CMS', description: 'Edit homepage content', icon: <FileText className="w-4 h-4" />, href: '/admin/homepage', category: 'Navigation' },
    { id: 'products', label: 'Products', description: 'Manage products', icon: <Package className="w-4 h-4" />, href: '/admin/products', category: 'Navigation' },
    { id: 'categories', label: 'Categories', description: 'Product categories', icon: <FolderTree className="w-4 h-4" />, href: '/admin/categories', category: 'Navigation' },
    { id: 'seo', label: 'SEO Settings', description: 'Meta & SEO config', icon: <Search className="w-4 h-4" />, href: '/admin/seo', category: 'Navigation' },
    { id: 'settings', label: 'Website Settings', description: 'Site configuration', icon: <Settings className="w-4 h-4" />, href: '/admin/settings', category: 'Navigation' },
    { id: 'sellers', label: 'Sellers', description: 'Manage sellers', icon: <Users className="w-4 h-4" />, href: '/admin/sellers', category: 'Management' },
    { id: 'subscriptions', label: 'Subscriptions', description: 'Plan management', icon: <CreditCard className="w-4 h-4" />, href: '/admin/subscriptions', category: 'Management' },
    { id: 'analytics', label: 'Analytics', description: 'Platform statistics', icon: <BarChart3 className="w-4 h-4" />, href: '/admin/analytics', category: 'Analytics' },
    { id: 'logout', label: 'Sign Out', description: 'Logout from admin', icon: <LogOut className="w-4 h-4" />, href: '/logout', category: 'Account' },
]

const navItems = [
    { group: 'WEB MANAGEMENT', items: [
        { icon: LayoutDashboard, label: 'Dashboard', href: '/admin' },
        { icon: Globe, label: 'Homepage CMS', href: '/admin/homepage' },
        { icon: Package, label: 'Products', href: '/admin/products' },
        { icon: FolderTree, label: 'Categories', href: '/admin/categories' },
        { icon: FileText, label: 'Content', href: '/admin/content' },
        { icon: Search, label: 'SEO', href: '/admin/seo' },
        { icon: Settings, label: 'Settings', href: '/admin/settings' },
    ]},
    { group: 'VENDOR MANAGEMENT', items: [
        { icon: Users, label: 'Sellers', href: '/admin/sellers' },
        { icon: CreditCard, label: 'Subscriptions', href: '/admin/subscriptions' },
        { icon: ShoppingBag, label: 'Deliveries', href: '/admin/deliveries' },
        { icon: AlertTriangle, label: 'Failed Deliveries', href: '/admin/deliveries/failed' },
        { icon: Store, label: 'Connected Shops', href: '/admin/connected-shops' },
        { icon: BarChart3, label: 'Analytics', href: '/admin/analytics' },
        { icon: RefreshCw, label: 'Sync Logs', href: '/admin/sync-logs' },
    ]},
    { group: 'SYSTEM', items: [
        { icon: Activity, label: 'System Health', href: '/admin/system' },
        { icon: Mail, label: 'Email Settings', href: '/admin/settings/email' },
        { icon: Shield, label: 'Security Center', href: '/admin/security' },
        { icon: Radio, label: 'Marketing', href: '/admin/marketing' },
        { icon: MessageSquare, label: 'Audit Logs', href: '/admin/audit-logs' },
    ]},
]

export default function AdminLayout({ children }: { children: React.ReactNode }) {
    const { auth = { user: null }, flash = {}, url = '' } = usePage<{ auth?: { user?: { name: string } | null }, flash?: { success?: string; error?: string }, url?: string }>().props
    const [collapsed, setCollapsed] = useState(false)

    return (
        <div className="min-h-screen bg-[#030712] app-shell flex">
            {/* Sidebar */}
            <aside className={`fixed top-0 left-0 h-full z-40 glass border-r border-white/5 flex flex-col transition-all duration-300 ${collapsed ? 'w-16' : 'w-64'}`}>
                {/* Logo */}
                <Link href="/admin" className="flex items-center gap-2.5 px-4 py-5 border-b border-white/5">
                    <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-cyan-400 to-sky-500 flex items-center justify-center flex-shrink-0">
                        <Target className="w-4 h-4 text-white" />
                    </div>
                    {!collapsed && <span className="text-sm font-bold text-white truncate">REDEEM Admin</span>}
                </Link>

                {/* Nav items */}
                <nav className="flex-1 overflow-y-auto py-4 px-2 space-y-6">
                    {navItems.map((group, gi) => (
                        <div key={gi}>
                            {!collapsed && <p className="px-3 text-[10px] font-semibold text-slate-500 uppercase tracking-[0.15em] mb-2">{group.group}</p>}
                            <div className="space-y-0.5">
                                {group.items.map((item) => {
                                    const isActive = url === item.href || url.startsWith(item.href + '/')
                                    return (
                                        <Link key={item.href} href={item.href}
                                            className={`flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm transition-all group ${
                                                isActive
                                                    ? 'bg-cyan-400/10 text-cyan-400 border-l-2 border-cyan-400 ml-[-2px]'
                                                    : 'text-slate-400 hover:text-white hover:bg-white/[0.03]'
                                            }`}>
                                            <item.icon className={`w-5 h-5 flex-shrink-0 ${isActive ? 'text-cyan-400' : 'text-slate-500 group-hover:text-slate-300'}`} />
                                            {!collapsed && <span className="truncate">{item.label}</span>}
                                        </Link>
                                    )
                                })}
                            </div>
                        </div>
                    ))}
                </nav>

                {/* User */}
                <div className="border-t border-white/5 p-3 flex items-center gap-3">
                    <div className="w-8 h-8 rounded-full bg-gradient-to-br from-cyan-400 to-sky-500 flex items-center justify-center text-xs font-bold text-white flex-shrink-0">
                        {auth.user?.name?.charAt(0) || 'A'}
                    </div>
                    {!collapsed && (
                        <div className="flex-1 min-w-0">
                            <p className="text-xs font-medium text-white truncate">{auth.user?.name}</p>
                            <Link href="/logout" method="post" as="button" className="text-[10px] text-slate-500 hover:text-red-400 transition-colors">Logout</Link>
                        </div>
                    )}
                </div>

                {/* Toggle */}
                <button onClick={() => setCollapsed(!collapsed)}
                    className="absolute -right-3 top-20 w-6 h-6 rounded-full bg-dark-600 border border-white/5 flex items-center justify-center text-slate-400 hover:text-white transition-colors">
                    {collapsed ? <ChevronRight className="w-3 h-3" /> : <ChevronLeft className="w-3 h-3" />}
                </button>
            </aside>

            {/* Main content */}
            <div className={`flex-1 transition-all duration-300 ${collapsed ? 'ml-16' : 'ml-64'}`}>
                {/* Top bar */}
                <header className="sticky top-0 z-30 glass border-b border-white/5 px-6 py-4 flex items-center justify-between">
                    <p className="text-sm text-slate-400">
                        Welcome back, <span className="text-white font-medium">{auth.user?.name}</span>
                    </p>
                    <div className="flex items-center gap-3">
                        <CommandPalette items={commandItems} placeholder="Search pages, settings..." />
                        <ThemeToggle />
                        <button className="relative text-slate-400 hover:text-white transition-colors">
                            <Bell className="w-4 h-4" />
                            <span className="absolute -top-1 -right-1 w-2 h-2 bg-cyan-400 rounded-full" />
                        </button>
                        <Link href="/" className="text-xs text-slate-500 hover:text-cyan-400 transition-colors flex items-center gap-1">
                            <Globe className="w-3 h-3" /> View Site
                        </Link>
                        <Link href="/logout" method="post" as="button"
                            className="flex items-center gap-1.5 text-xs text-slate-500 hover:text-red-400 transition-colors">
                            <LogOut className="w-3 h-3" /> Sign Out
                        </Link>
                    </div>
                </header>

                {/* Flash messages */}
                {flash.success && (
                    <div className="mx-6 mt-4 p-3 bg-emerald-400/10 border border-emerald-400/20 rounded-lg text-emerald-400 text-sm">{flash.success}</div>
                )}
                {flash.error && (
                    <div className="mx-6 mt-4 p-3 bg-red-400/10 border border-red-400/20 rounded-lg text-red-400 text-sm">{flash.error}</div>
                )}

                {/* Page content */}
                <motion.main initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }} className="p-6">
                    {children}
                </motion.main>
            </div>
        </div>
    )
}
