'use client';

import { useState, useMemo, createContext, useContext, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import {
  LayoutDashboard,
  Bot,
  BookOpen,
  ClipboardList,
  Server,
  Activity,
  Terminal,
  Shield,
  FileSearch,
  MessageSquare,
  Building2,
  Settings,
  Users,
  ChevronRight,
  PanelLeftClose,
  PanelLeft,
  CreditCard,
  Smartphone,
  Database,
  Boxes,
  Gift,
  Bell,
  Tags,
  Radio,
  Megaphone,
  Users2,
} from 'lucide-react';

/* ---------- Sidebar context for collapse state ---------- */

interface SidebarContextValue {
  collapsed: boolean;
  setCollapsed: (v: boolean) => void;
}

const SidebarContext = createContext<SidebarContextValue>({
  collapsed: false,
  setCollapsed: () => {},
});

export const useSidebar = () => useContext(SidebarContext);

/* ---------- Nav config ---------- */

interface NavItem {
  key: string;
  label: string;
  href: string;
  icon: React.ReactNode;
  children?: { label: string; href: string }[];
}

const iconClass = 'h-4 w-4 shrink-0';

/* ---------- Helpers ---------- */

function isActive(pathname: string, href: string) {
  return pathname === href || pathname.startsWith(href + '/');
}

function isGroupActive(pathname: string, item: NavItem) {
  if (isActive(pathname, item.href)) return true;
  return item.children?.some((c) => isActive(pathname, c.href)) ?? false;
}

/* ---------- Tooltip for collapsed mode ---------- */

function Tooltip({ children, label }: { children: React.ReactNode; label: string }) {
  return (
    <div className="relative group/tip">
      {children}
      <div
        className="absolute left-full top-1/2 -translate-y-1/2 ml-2 px-2.5 py-1 rounded-md
                    bg-popover text-popover-foreground text-xs font-medium whitespace-nowrap
                    shadow-md border opacity-0 pointer-events-none
                    group-hover/tip:opacity-100 transition-opacity duration-150 z-50"
      >
        {label}
      </div>
    </div>
  );
}

/* ---------- Main component ---------- */

export function Sidebar() {
  const pathname = usePathname();
  const { t } = useTranslation('sidebar');
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
  const [collapsed, setCollapsed] = useState(false);
  const [isPlatformAdmin, setIsPlatformAdmin] = useState(false);

  useEffect(() => {
    try {
      const raw = localStorage.getItem('user');
      if (raw) {
        const user = JSON.parse(raw) as { roles?: string[] };
        setIsPlatformAdmin(
          Array.isArray(user.roles) &&
          (user.roles.includes('platform_admin') || user.roles.includes('platform_super_admin')),
        );
      }
    } catch { /* ignore */ }
  }, []);

  const platformAdminItems: NavItem[] = useMemo(() => [
    { key: 'dashboard', label: t('dashboard'), href: '/dashboard', icon: <LayoutDashboard className={iconClass} /> },
    { key: 'tenants', label: t('tenants'), href: '/tenants', icon: <Building2 className={iconClass} /> },
    { key: 'users', label: t('users'), href: '/users', icon: <Users className={iconClass} /> },
    { key: 'appVersions', label: t('appVersions'), href: '/app-versions', icon: <Smartphone className={iconClass} /> },
    { key: 'referral', label: t('referral'), href: '/referral', icon: <Gift className={iconClass} /> },
    { key: 'tenantTags', label: t('tenantTags'), href: '/tenant-tags', icon: <Tags className={iconClass} /> },
    { key: 'notificationChannels', label: t('notificationChannels'), href: '/notification-channels', icon: <Radio className={iconClass} /> },
    { key: 'campaigns', label: t('campaigns'), href: '/campaigns', icon: <Megaphone className={iconClass} /> },
    { key: 'segments', label: t('segments'), href: '/segments', icon: <Users2 className={iconClass} /> },
    { key: 'notifications', label: t('notifications'), href: '/notifications', icon: <Bell className={iconClass} /> },
    { key: 'serverPool', label: t('serverPool'), href: '/server-pool', icon: <Database className={iconClass} /> },
    { key: 'openclawInstances', label: t('openclawInstances'), href: '/openclaw-instances', icon: <Boxes className={iconClass} /> },
    {
      key: 'billing',
      label: t('billing'),
      href: '/billing/plans',
      icon: <CreditCard className={iconClass} />,
      children: [
        { label: t('billingPlans'), href: '/billing/plans' },
        { label: t('billingOverview'), href: '/billing' },
        { label: t('billingInvoices'), href: '/billing/invoices' },
      ],
    },
    { key: 'settings', label: t('settings'), href: '/settings', icon: <Settings className={iconClass} /> },
  ], [t]);

  const tenantNavItems: NavItem[] = useMemo(() => [
    { key: 'dashboard', label: t('dashboard'), href: '/dashboard', icon: <LayoutDashboard className={iconClass} /> },
    { key: 'myOrg', label: t('myOrg'), href: '/my-org', icon: <Users className={iconClass} /> },
    {
      key: 'agentConfig',
      label: t('agentConfig'),
      href: '/agent-config',
      icon: <Bot className={iconClass} />,
      children: [
        { label: t('enginePrompt'), href: '/agent-config' },
        { label: t('sdkConfig'), href: '/agent-config/sdk' },
        { label: t('skills'), href: '/agent-config/skills' },
        { label: t('hooks'), href: '/agent-config/hooks' },
      ],
    },
    { key: 'runbooks', label: t('runbooks'), href: '/runbooks', icon: <BookOpen className={iconClass} /> },
    { key: 'standingOrders', label: t('standingOrders'), href: '/standing-orders', icon: <ClipboardList className={iconClass} /> },
    {
      key: 'servers',
      label: t('servers'),
      href: '/servers',
      icon: <Server className={iconClass} />,
      children: [
        { label: t('allServers'), href: '/servers' },
        { label: t('clusters'), href: '/servers/clusters' },
      ],
    },
    {
      key: 'monitoring',
      label: t('monitoring'),
      href: '/monitoring/alert-rules',
      icon: <Activity className={iconClass} />,
      children: [
        { label: t('alertRules'), href: '/monitoring/alert-rules' },
        { label: t('healthChecks'), href: '/monitoring/health-checks' },
        { label: t('metrics'), href: '/monitoring/metrics' },
      ],
    },
    { key: 'terminal', label: t('terminal'), href: '/terminal', icon: <Terminal className={iconClass} /> },
    {
      key: 'security',
      label: t('security'),
      href: '/security/risk-rules',
      icon: <Shield className={iconClass} />,
      children: [
        { label: t('riskRules'), href: '/security/risk-rules' },
        { label: t('credentials'), href: '/security/credentials' },
        { label: t('roles'), href: '/security/roles' },
        { label: t('permissions'), href: '/security/permissions' },
      ],
    },
    {
      key: 'audit',
      label: t('audit'),
      href: '/audit/logs',
      icon: <FileSearch className={iconClass} />,
      children: [
        { label: t('logs'), href: '/audit/logs' },
        { label: t('sessionReplay'), href: '/audit/replay' },
      ],
    },
    { key: 'communication', label: t('communication'), href: '/communication', icon: <MessageSquare className={iconClass} /> },
    {
      key: 'billing',
      label: t('billing'),
      href: '/billing',
      icon: <CreditCard className={iconClass} />,
      children: [
        { label: t('billingPlans'), href: '/billing/plans' },
        { label: t('billingOverview'), href: '/billing' },
        { label: t('billingInvoices'), href: '/billing/invoices' },
      ],
    },
    { key: 'settings', label: t('settings'), href: '/settings', icon: <Settings className={iconClass} /> },
  ], [t]);

  const navItems = isPlatformAdmin ? platformAdminItems : tenantNavItems;

  const toggle = (key: string) =>
    setExpanded((prev) => ({ ...prev, [key]: !prev[key] }));

  return (
    <SidebarContext.Provider value={{ collapsed, setCollapsed }}>
      <aside
        className={cn(
          'bg-card/50 backdrop-blur-sm border-r flex flex-col transition-all duration-200 ease-in-out',
          collapsed ? 'w-16' : 'w-60',
        )}
      >
        {/* Logo area */}
        <div className={cn('border-b flex items-center', collapsed ? 'px-3 py-4 justify-center' : 'px-4 py-4')}>
          <div className="flex items-center gap-2.5 min-w-0">
            <img src="/icons/favicon.svg" alt="iAgent" className="w-8 h-8 shrink-0" />
            {!collapsed && (
              <div className="min-w-0">
                <h1 className="text-sm font-semibold tracking-tight truncate">{t('appName')}</h1>
                <p className="text-[10px] text-muted-foreground leading-none mt-0.5">{t('appSubtitle')}</p>
              </div>
            )}
          </div>
        </div>

        {/* Navigation */}
        <nav className="flex-1 py-2 px-2 space-y-0.5 overflow-y-auto overflow-x-hidden">
          {navItems.map((item) => {
            const hasChildren = item.children && item.children.length > 0;
            const groupActive = isGroupActive(pathname, item);
            const isOpen = expanded[item.key] ?? groupActive;

            /* ---- Collapsed: icon-only with tooltip ---- */
            if (collapsed) {
              const linkTarget = hasChildren
                ? item.children![0].href
                : item.href;
              return (
                <Tooltip key={item.key} label={item.label}>
                  <Link
                    href={linkTarget}
                    className={cn(
                      'flex items-center justify-center h-9 w-full rounded-md transition-colors',
                      groupActive
                        ? 'bg-primary/10 text-primary'
                        : 'text-muted-foreground hover:bg-accent hover:text-foreground',
                    )}
                  >
                    {item.icon}
                  </Link>
                </Tooltip>
              );
            }

            /* ---- Expanded: no children ---- */
            if (!hasChildren) {
              return (
                <Link
                  key={item.key}
                  href={item.href}
                  className={cn(
                    'flex items-center gap-2.5 px-2.5 py-2 rounded-md text-[13px] transition-colors',
                    isActive(pathname, item.href)
                      ? 'bg-primary/10 text-primary font-medium'
                      : 'text-muted-foreground hover:bg-accent hover:text-foreground',
                  )}
                >
                  {item.icon}
                  <span className="truncate">{item.label}</span>
                </Link>
              );
            }

            /* ---- Expanded: with children ---- */
            return (
              <div key={item.key}>
                <button
                  onClick={() => toggle(item.key)}
                  className={cn(
                    'flex items-center gap-2.5 w-full px-2.5 py-2 rounded-md text-[13px] transition-colors',
                    groupActive
                      ? 'text-primary'
                      : 'text-muted-foreground hover:bg-accent hover:text-foreground',
                  )}
                >
                  {item.icon}
                  <span className="flex-1 text-left truncate">{item.label}</span>
                  <ChevronRight
                    className={cn(
                      'h-3.5 w-3.5 shrink-0 transition-transform duration-200',
                      isOpen && 'rotate-90',
                    )}
                  />
                </button>
                {isOpen && (
                  <div className="ml-[18px] mt-0.5 space-y-0.5 border-l border-border/50 pl-2.5">
                    {item.children!.map((child) => (
                      <Link
                        key={child.href}
                        href={child.href}
                        className={cn(
                          'flex items-center px-2.5 py-1.5 rounded-md text-xs transition-colors',
                          isActive(pathname, child.href)
                            ? 'bg-primary/10 text-primary font-medium'
                            : 'text-muted-foreground hover:bg-accent hover:text-foreground',
                        )}
                      >
                        <span className="truncate">{child.label}</span>
                      </Link>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </nav>

        {/* Collapse toggle at bottom */}
        <div className="border-t p-2">
          <button
            onClick={() => setCollapsed(!collapsed)}
            className={cn(
              'flex items-center gap-2.5 w-full rounded-md text-xs text-muted-foreground',
              'hover:bg-accent hover:text-foreground transition-colors',
              collapsed ? 'justify-center h-9' : 'px-2.5 py-2',
            )}
          >
            {collapsed ? (
              <PanelLeft className="h-4 w-4 shrink-0" />
            ) : (
              <>
                <PanelLeftClose className="h-4 w-4 shrink-0" />
                <span>{t('collapse')}</span>
              </>
            )}
          </button>
        </div>
      </aside>
    </SidebarContext.Provider>
  );
}
