'use client';

import { useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import {
  LayoutDashboard,
  Users,
  CreditCard,
  Key,
  KeyRound,
  BarChart3,
  Settings,
  Package,
  LogOut,
  Menu,
  X,
  ScrollText,
  Sun,
  Moon,
  Ticket,
  Tag,
  Gift,
  Palette,
  Wallet,
  Bell,
  BookOpen,
  Activity,
  FileText,
  Shield,
  MessageSquare,
  Megaphone,
  ClipboardList,
  Workflow,
  Beaker,
  Crosshair,
  Bug,
  HeartPulse,
  FileSearch,
  FlaskConical,
  BrainCircuit,
  TrendingDown,
  Building2,
  LifeBuoy,
  Coins,
  ListOrdered,
  Webhook,
  Database,
  Star,
  Store,
  Mail,
  Timer,
  Radio,
  ShieldBan,
  Wrench,
  MonitorSmartphone,
  Bot,
  Globe,
  Download,
  Server,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuth } from '@/lib/auth-context';
import { useTheme } from '@/lib/theme-context';
import { ProductSwitcher } from '@/components/product-switcher';

const navItems = [
  { href: '/', label: 'Dashboard', icon: LayoutDashboard },
  { href: '/users', label: 'Users', icon: Users },
  { href: '/subscriptions', label: 'Subscriptions', icon: CreditCard },
  { href: '/licenses', label: 'Licenses', icon: KeyRound },
  { href: '/tokens', label: 'API Tokens', icon: Key },
  { href: '/usage', label: 'Usage Analytics', icon: BarChart3 },
  { href: '/invitations', label: 'Invitations', icon: Ticket },
  { href: '/promos', label: 'Promo Codes', icon: Tag },
  { href: '/referrals', label: 'Referrals', icon: Gift },
  { href: '/broadcasts', label: 'Broadcasts', icon: Megaphone },
  { href: '/surveys', label: 'Surveys', icon: ClipboardList },
  { href: '/themes', label: 'Themes', icon: Palette },
  { href: '/billing', label: 'Billing', icon: Wallet },
  { href: '/products', label: 'Products', icon: Package },
  { href: '/notifications', label: 'Notifications', icon: Bell },
  { href: '/docs', label: 'Docs & Runbooks', icon: BookOpen },
  { href: '/flags', label: 'Feature Flags', icon: Settings },
  { href: '/audit', label: 'Audit Log', icon: ScrollText },
  { href: '/actiontrail', label: 'ActionTrail', icon: Crosshair },
  { href: '/timeline', label: 'Timeline', icon: Workflow },
  { href: '/organizations', label: 'Organizations', icon: Building2 },
  { href: '/support', label: 'Support Cases', icon: LifeBuoy },
  { href: '/ai-budgets', label: 'AI Budgets', icon: Coins },
  { href: '/waitlist', label: 'Waitlist', icon: ListOrdered },
  { href: '/webhooks', label: 'Webhooks', icon: Webhook },
  { href: '/knowledge', label: 'Knowledge Bases', icon: Database },
  { href: '/agent-evals', label: 'Agent Evals', icon: FlaskConical },
  { href: '/reviews', label: 'Reviews', icon: Star },
  { href: '/marketplace', label: 'Marketplace', icon: Store },
  { href: '/delivery', label: 'Delivery Log', icon: Mail },
  { href: '/jobs', label: 'Scheduled Jobs', icon: Timer },
  { href: '/agent-runtime', label: 'Agent Runtime', icon: Bot },
  { href: '/event-subscriptions', label: 'Event Subs', icon: Radio },
  { href: '/ip-rules', label: 'IP Rules', icon: ShieldBan },
  { href: '/maintenance', label: 'Maintenance', icon: Wrench },
  { href: '/sessions-admin', label: 'Sessions', icon: MonitorSmartphone },
  { href: '/status', label: 'Status', icon: Globe },
  { href: '/gdpr-export', label: 'GDPR Export', icon: Download },
  { href: '/experiments', label: 'Experiments', icon: FlaskConical },
  { href: '/predictive/at-risk', label: 'Predictive', icon: TrendingDown },
  { href: '/ops', label: 'Mission Control', icon: Activity },
  { href: '/ops/client-logs', label: 'Client Logs', icon: FileText },
  { href: '/ops/telemetry-policies', label: 'Telemetry Policies', icon: Shield },
  { href: '/ops/ab-testing', label: 'A/B Testing', icon: Beaker },
  { href: '/debug-sessions', label: 'Debug Sessions', icon: Bug },
  { href: '/health-dashboard', label: 'Health Dashboard', icon: HeartPulse },
  { href: '/extraction', label: 'Extraction', icon: FileSearch },
  { href: '/ai-diagnostics', label: 'AI Diagnostics', icon: BrainCircuit },
  { href: '/feedback', label: 'User Feedback', icon: MessageSquare },
  { href: '/ops/secrets', label: 'Secrets Manager', icon: KeyRound },
  { href: '/devops', label: 'DevOps', icon: Server },
  { href: '/settings', label: 'Settings', icon: Settings },
];

export function SidebarNav() {
  const pathname = usePathname();
  const router = useRouter();
  const { user, logout } = useAuth();
  const { resolved, setTheme } = useTheme();
  const [mobileOpen, setMobileOpen] = useState(false);

  const handleLogout = () => {
    logout();
    router.replace('/login');
  };

  const initials = user?.name
    ? user.name
        .split(' ')
        .map(w => w[0])
        .join('')
        .toUpperCase()
        .slice(0, 2)
    : '??';

  const sidebarContent = (
    <>
      {/* Logo */}
      <div className="flex h-16 items-center justify-between border-b px-6">
        <div className="flex items-center gap-2">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary">
            <LayoutDashboard className="h-4 w-4 text-primary-foreground" />
          </div>
          <div>
            <h1 className="text-sm font-bold">Admin</h1>
            <p className="text-[10px] text-muted-foreground">Admin Console</p>
          </div>
        </div>
        {/* Mobile close button */}
        <button
          className="md:hidden text-muted-foreground hover:text-foreground"
          onClick={() => setMobileOpen(false)}
        >
          <X className="h-5 w-5" />
        </button>
      </div>

      {/* Product Switcher */}
      <ProductSwitcher />

      {/* Navigation */}
      <nav className="flex-1 space-y-1 px-3 py-4">
        {navItems.map(item => {
          const isActive =
            item.href === '/'
              ? pathname === '/'
              : pathname === item.href ||
                (pathname.startsWith(item.href + '/') &&
                  !navItems.some(
                    other =>
                      other.href !== item.href &&
                      other.href.startsWith(item.href + '/') &&
                      pathname.startsWith(other.href)
                  ));
          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={() => setMobileOpen(false)}
              className={cn(
                'flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors',
                isActive
                  ? 'bg-primary text-primary-foreground'
                  : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
              )}
            >
              <item.icon className="h-4 w-4" />
              {item.label}
            </Link>
          );
        })}
      </nav>

      {/* Footer — theme toggle + user info + logout */}
      <div className="border-t p-4 space-y-3">
        <button
          onClick={() => setTheme(resolved === 'dark' ? 'light' : 'dark')}
          className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-colors"
        >
          {resolved === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
          {resolved === 'dark' ? 'Light Mode' : 'Dark Mode'}
        </button>
        <div className="flex items-center gap-3">
          <div className="flex h-8 w-8 items-center justify-center rounded-full bg-muted text-xs font-bold">
            {initials}
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium truncate">{user?.name ?? 'Admin'}</p>
            <p className="text-xs text-muted-foreground truncate">{user?.email ?? ''}</p>
          </div>
          <button
            onClick={handleLogout}
            title="Sign out"
            className="text-muted-foreground hover:text-foreground"
          >
            <LogOut className="h-4 w-4" />
          </button>
        </div>
      </div>
    </>
  );

  return (
    <>
      {/* Mobile hamburger */}
      <div className="fixed top-0 left-0 right-0 z-40 flex h-14 items-center border-b bg-card px-4 md:hidden">
        <button onClick={() => setMobileOpen(true)}>
          <Menu className="h-6 w-6" />
        </button>
        <span className="ml-3 text-sm font-bold">Platform Admin</span>
      </div>
      {/* Spacer for mobile top bar */}
      <div className="h-14 md:hidden" />

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

      {/* Sidebar — always visible on md+, slide-in on mobile */}
      <aside
        className={cn(
          'fixed inset-y-0 left-0 z-50 flex w-64 flex-col border-r bg-card transition-transform duration-200',
          'max-md:translate-x-[-100%]',
          mobileOpen && 'max-md:translate-x-0'
        )}
      >
        {sidebarContent}
      </aside>
    </>
  );
}
