'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,
  Beaker,
} 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: '/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: '/feedback', label: 'User Feedback', icon: MessageSquare },
  { href: '/ops/secrets', label: 'Secrets Manager', icon: KeyRound },
  { 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>
    </>
  );
}
