'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import {
  LayoutDashboard,
  BarChart3,
  Cpu,
  Key,
  Code2,
  Settings,
  LogOut,
  Menu,
  X,
  Sun,
  Moon,
  HeartPulse,
  Sparkles,
  Server,
} from 'lucide-react';
import { useAuth } from '@/lib/auth';

const THEME_STORAGE_KEY = 'bytelyst.theme.v1';
const SIDEBAR_STORAGE_KEY = 'bytelyst.devops.sidebar.collapsed.v1';
const THEME_EVENT = 'bytelyst-theme-change';
type Theme = 'light' | 'dark';

const navItems = [
  { href: '/', label: 'Dashboard', icon: LayoutDashboard },
  { href: '/hermes', label: 'Hermes', icon: Sparkles },
  { href: '/health', label: 'Health', icon: HeartPulse },
  { href: '/metrics', label: 'Metrics', icon: BarChart3 },
  { href: '/vm', label: 'VM Health', icon: Server },
  { href: '/system', label: 'System', icon: Cpu },
  { href: '/env', label: 'Environment', icon: Key },
  { href: '/code-quality', label: 'Code Quality', icon: Code2 },
  { href: '/settings/cosmos', label: 'Settings', icon: Settings },
];

export function SidebarNav() {
  const pathname = usePathname();
  const router = useRouter();
  const { user, logout } = useAuth();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const [theme, setTheme] = useState<Theme>('dark');

  useEffect(() => {
    function handleThemeChange(event: Event) {
      const next = (event as CustomEvent<Theme>).detail;
      if (next === 'light' || next === 'dark') {
        setTheme(next);
        applyTheme(next);
      }
    }

    try {
      const savedTheme = window.localStorage.getItem(THEME_STORAGE_KEY) as Theme | null;
      const legacyTheme = window.localStorage.getItem('theme') as Theme | null;
      const nextTheme = savedTheme === 'light' || savedTheme === 'dark'
        ? savedTheme
        : legacyTheme === 'light' || legacyTheme === 'dark'
          ? legacyTheme
          : 'dark';
      setTheme(nextTheme);
      applyTheme(nextTheme);

      setCollapsed(window.localStorage.getItem(SIDEBAR_STORAGE_KEY) === 'true');
    } catch {
      applyTheme('dark');
    }

    window.addEventListener(THEME_EVENT, handleThemeChange);
    return () => window.removeEventListener(THEME_EVENT, handleThemeChange);
  }, []);

  function applyTheme(next: Theme) {
    document.documentElement.setAttribute('data-theme', next);
    document.documentElement.classList.toggle('dark', next === 'dark');
  }

  function toggleTheme() {
    const next = theme === 'dark' ? 'light' : 'dark';
    setTheme(next);
    applyTheme(next);
    try {
      window.localStorage.setItem(THEME_STORAGE_KEY, next);
      window.localStorage.setItem('theme', next);
      window.dispatchEvent(new CustomEvent(THEME_EVENT, { detail: next }));
    } catch {
      // localStorage can be unavailable in private browsing.
    }
  }

  function toggleCollapsed() {
    setCollapsed((current) => {
      const next = !current;
      try {
        window.localStorage.setItem(SIDEBAR_STORAGE_KEY, String(next));
      } catch {
        // ignore
      }
      return next;
    });
  }

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

  const initials = user?.email
    ? user.email.slice(0, 2).toUpperCase()
    : '??';

  const sidebarContent = (isCollapsed = false, showCollapseControl = false) => (
    <>
      {/* Logo */}
      <div className="flex h-16 items-center justify-between border-b border-[var(--bl-border)] px-4">
        <div className="flex min-w-0 items-center gap-2">
          <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--bl-accent)]">
            <LayoutDashboard className="h-4 w-4 text-white" />
          </div>
          <div className={isCollapsed ? 'sr-only' : 'min-w-0'}>
            <h1 className="truncate text-sm font-bold text-[var(--bl-text-primary)]">DevOps</h1>
            <p className="truncate text-[10px] text-[var(--bl-text-secondary)]">Dashboard</p>
          </div>
        </div>
        {showCollapseControl && (
          <button
            className="hidden rounded-md p-1.5 text-[var(--bl-text-secondary)] hover:bg-[var(--bl-surface-muted)] hover:text-[var(--bl-text-primary)] md:inline-flex"
            onClick={toggleCollapsed}
            aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
            title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          >
            <Menu className="h-4 w-4" />
          </button>
        )}
        {/* Mobile close button */}
        <button
          className="rounded-md p-1.5 text-[var(--bl-text-secondary)] hover:bg-[var(--bl-surface-muted)] hover:text-[var(--bl-text-primary)] md:hidden"
          onClick={() => setMobileOpen(false)}
          aria-label="Close navigation"
        >
          <X className="h-5 w-5" />
        </button>
      </div>

      {/* Navigation */}
      <nav className="flex-1 space-y-1 px-3 py-4">
        {navItems.map(item => {
          const isActive = pathname === item.href ||
            (item.href !== '/' && pathname.startsWith(item.href));
          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={() => setMobileOpen(false)}
              title={isCollapsed ? item.label : undefined}
              className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
                isActive
                  ? 'bg-[var(--bl-accent)] text-[var(--bl-accent-foreground)]'
                  : 'text-[var(--bl-text-secondary)] hover:bg-[var(--bl-surface-muted)] hover:text-[var(--bl-text-primary)]'
              }`}
            >
              <item.icon className="h-4 w-4 shrink-0" />
              <span className={isCollapsed ? 'sr-only' : 'truncate'}>{item.label}</span>
            </Link>
          );
        })}
      </nav>

      {/* Footer — theme toggle + user info + logout */}
      <div className="space-y-3 border-t border-[var(--bl-border)] p-4">
        <button
          onClick={toggleTheme}
          className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-[var(--bl-text-secondary)] transition-colors hover:bg-[var(--bl-surface-muted)] hover:text-[var(--bl-text-primary)]"
          aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
          title={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
        >
          {theme === 'dark' ? <Sun className="h-4 w-4 shrink-0" /> : <Moon className="h-4 w-4 shrink-0" />}
          <span className={isCollapsed ? 'sr-only' : 'truncate'}>{theme === 'dark' ? 'Light Mode' : 'Dark Mode'}</span>
        </button>
        <div className="flex items-center gap-3">
          <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--bl-surface-muted)] text-xs font-bold text-[var(--bl-text-secondary)]">
            {initials}
          </div>
          <div className={isCollapsed ? 'sr-only' : 'min-w-0 flex-1'}>
            <p className="truncate text-sm font-medium text-[var(--bl-text-primary)]">{user?.email ?? 'Admin'}</p>
            <p className="truncate text-xs text-[var(--bl-text-secondary)]">{user?.role ?? 'admin'}</p>
          </div>
          <button
            onClick={handleLogout}
            title="Sign out"
            aria-label="Sign out"
            className="rounded-md p-1.5 text-[var(--bl-text-secondary)] hover:bg-[var(--bl-surface-muted)] hover:text-[var(--bl-text-primary)]"
          >
            <LogOut className="h-4 w-4" />
          </button>
        </div>
      </div>
    </>
  );

  return (
    <>
      {/* Mobile hamburger */}
      <div className="fixed left-0 right-0 top-0 z-30 flex h-14 items-center border-b border-[var(--bl-border)] bg-[var(--bl-surface-card)] px-4 text-[var(--bl-text-primary)] md:hidden">
        <button onClick={() => setMobileOpen(true)} aria-label="Open navigation">
          <Menu className="h-6 w-6" />
        </button>
        <span className="ml-3 text-sm font-bold">DevOps Dashboard</span>
      </div>

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

      {/* Sidebar — fixed on mobile, in-flow and collapsible on desktop */}
      <aside
        className={`fixed inset-y-0 left-0 z-50 flex w-64 flex-col border-r border-[var(--bl-border)] bg-[var(--bl-surface-card)] text-[var(--bl-text-primary)] shadow-[var(--bl-shadow-md)] transition-transform duration-200 md:hidden ${mobileOpen ? 'translate-x-0' : '-translate-x-full'}`}
      >
        {sidebarContent(false, false)}
      </aside>
      <aside
        className={`hidden border-r border-[var(--bl-border)] bg-[var(--bl-surface-card)] text-[var(--bl-text-primary)] md:sticky md:top-0 md:flex md:h-screen md:shrink-0 md:flex-col ${collapsed ? 'md:w-20' : 'md:w-64'}`}
      >
        {sidebarContent(collapsed, true)}
      </aside>
    </>
  );
}
