'use client';

import { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { LayoutDashboard, ShoppingBag, CalendarDays, CalendarCheck, Bot, MessageSquare, BarChart3, Settings, Users, BookOpen, UserCircle, GitBranch, LayoutGrid, Store, CreditCard, Cpu, LineChart, Headphones, Shield, Database, Phone, KeyRound, LogOut, ExternalLink, ChevronUp, Zap, Code2, LogIn, Loader2, Paintbrush, Globe } from 'lucide-react';
import AppLogo from '@client/components/ui/AppLogo';
import { useAuth } from '@client/contexts/AuthContext';
import { useLiveCounts } from '@client/contexts/LiveCountsContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import LanguageSwitcher from '@client/components/ui/LanguageSwitcher';
import { useBranding } from '@client/contexts/BrandingContext';
import { usePlanFeatures } from '@client/contexts/PlanFeaturesContext';

interface NavItem {
  label: string;
  icon: React.ReactNode;
  href: string;
  badge?: number;
  badgeVariant?: 'danger' | 'warning' | 'info';
  disabled?: boolean;
}

interface NavGroup {
  label: string;
  items: NavItem[];
}

interface SidebarProps {
  isCollapsed: boolean;
  onToggle: () => void;
  isAdminMode?: boolean;
  onToggleAdminMode?: () => void;
  impersonatingName?: string;
  onExitImpersonation?: () => void;
  exitingImpersonation?: boolean;
}

export default function Sidebar({ isCollapsed, onToggle, isAdminMode = false, onToggleAdminMode, impersonatingName, onExitImpersonation, exitingImpersonation }: SidebarProps) {
  const pathname = usePathname();
  const { userRecord, signOut } = useAuth();
  const { t } = useLanguage();
  const { branding } = useBranding();
  const restaurantLogoUrl = userRecord?.restaurants?.logo_url || null;
  const { pendingOrders, pendingBookings, needsAgentCount } = useLiveCounts();
  const { hasFeature } = usePlanFeatures();
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  const profileMenuRef = useRef<HTMLDivElement>(null);

  const adminNavGroups: NavGroup[] = [
    {
      label: t('admin.title', 'Admin'),
      items: [
        { label: t('nav.dashboard', 'Dashboard'), icon: <LayoutGrid size={18} />, href: '/admin/dashboard' },
        { label: t('nav.restaurants', 'Restaurants'), icon: <Store size={18} />, href: '/admin/restaurants' },
        { label: t('nav.adminOrders', 'Orders'), icon: <ShoppingBag size={18} />, href: '/admin/orders' },
        { label: t('nav.adminBookings', 'Table Bookings'), icon: <CalendarCheck size={18} />, href: '/admin/bookings' },
        { label: t('nav.billing', 'Billing'), icon: <CreditCard size={18} />, href: '/admin/billing' },
      ],
    },
    {
      label: t('admin.platform', 'Platform'),
      items: [
        { label: t('nav.platformKeys', 'Platform Keys'), icon: <Cpu size={18} />, href: '/admin/ai-settings' },
        { label: t('nav.analytics', 'Analytics'), icon: <LineChart size={18} />, href: '/admin/platform-analytics' },
        { label: t('nav.support', 'Support Tools'), icon: <Headphones size={18} />, href: '/admin/support' },
        { label: t('nav.branding', 'Branding'), icon: <Paintbrush size={18} />, href: '/admin/branding' },
        { label: t('nav.languages', 'Languages'), icon: <Globe size={18} />, href: '/admin/languages' },
      ],
    },
  ];

  const restaurantNavGroups: NavGroup[] = [
    {
      label: t('nav.operations', 'Operations'),
      items: [
        { label: t('nav.agentOverview', 'Agent Overview'), icon: <LayoutDashboard size={18} />, href: '/restaurant-dashboard' },
        { label: t('nav.orders', 'Orders'), icon: <ShoppingBag size={18} />, href: '/order-management', badge: pendingOrders > 0 ? pendingOrders : undefined, badgeVariant: 'danger' },
        { label: t('nav.reservations', 'Reservations'), icon: <CalendarDays size={18} />, href: '/table-booking-management', badge: pendingBookings > 0 ? pendingBookings : undefined, badgeVariant: 'info' },
      ],
    },
    {
      label: t('nav.aiAgent', 'AI Agent'),
      items: [
        { label: t('nav.aiConfiguration', 'AI Configuration'), icon: <Bot size={18} />, href: '/ai-agent-config', disabled: !hasFeature('chat_agent') },
        { label: t('nav.knowledgeBase', 'Knowledge Base'), icon: <Database size={18} />, href: '/knowledge-base', disabled: !hasFeature('knowledge_base') },
        { label: t('nav.telephone', 'Telephone'), icon: <Phone size={18} />, href: '/telephone', disabled: !hasFeature('voice_agent') },
        { label: t('nav.chatWidget', 'Chat Widget'), icon: <Code2 size={18} />, href: '/widget-settings' },
        { label: t('nav.conversations', 'Conversations'), icon: <MessageSquare size={18} />, href: '/conversations', badge: needsAgentCount > 0 ? needsAgentCount : undefined, badgeVariant: 'warning' },
      ],
    },
    {
      label: t('nav.restaurant', 'Restaurant'),
      items: [
        { label: t('nav.menuManagement', 'Menu Management'), icon: <BookOpen size={18} />, href: '/menu-management' },
        { label: t('nav.customers', 'Customers'), icon: <UserCircle size={18} />, href: '/customers' },
        { label: t('nav.staff', 'Staff & Team'), icon: <Users size={18} />, href: '/staff' },
        { label: t('nav.branches', 'Branches'), icon: <GitBranch size={18} />, href: '/branch-management', disabled: !hasFeature('multi_branch') },
      ],
    },
    {
      label: t('nav.insights', 'Insights'),
      items: [
        { label: t('nav.analytics', 'Analytics'), icon: <BarChart3 size={18} />, href: '/analytics', disabled: !hasFeature('analytics') },
        { label: t('nav.settings', 'Settings'), icon: <Settings size={18} />, href: '/restaurant-settings' },
      ],
    },
  ];

  const navGroups = isAdminMode ? adminNavGroups : restaurantNavGroups;

  const userName = userRecord?.name || t('sidebar.defaultUserName', 'User');
  const userEmail = userRecord?.email || '';
  const isAdminRole = userRecord?.role === 'superadmin' || userRecord?.role === 'support';
  const userRole = isAdminRole ? t('auth.platformAdmin', 'Platform Admin') : t('auth.restaurantOwner', 'Restaurant Owner');
  const userInitials = userName.split(' ').map((n: string) => n[0]).join('').toUpperCase().slice(0, 2) || 'MK';

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (profileMenuRef.current && !profileMenuRef.current.contains(e.target as Node)) {
        setShowProfileMenu(false);
      }
    };
    if (showProfileMenu) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [showProfileMenu]);

  useEffect(() => { setShowProfileMenu(false); }, [pathname]);

  const restaurantName = userRecord?.restaurants?.name || t('sidebar.defaultRestaurantName', 'My Restaurant');
  const siteTitle = branding.site_title;

  const getBadgeClass = (variant?: 'danger' | 'warning' | 'info') => {
    switch (variant) {
      case 'danger': return 'bg-danger text-white';
      case 'warning': return 'bg-warning text-white';
      case 'info': return 'bg-info text-white';
      default: return 'bg-primary text-white';
    }
  };

  return (
    <aside
      className="flex flex-col h-full relative"
      style={{
        width: isCollapsed ? '64px' : '240px',
        transition: 'width 300ms ease',
        backgroundColor: isAdminMode ? 'hsl(231, 40%, 10%)' : 'hsl(var(--surface))',
        borderRight: '1px solid hsl(var(--border))',
        overflow: 'hidden',
      }}
    >
      <div className="flex items-center h-16 px-4 shrink-0" style={{ borderBottom: `1px solid ${isAdminMode ? 'rgba(255,255,255,0.1)' : 'hsl(var(--border))'}` }}>
        <div className="flex items-center gap-2.5 min-w-0">
          <AppLogo
              src={isAdminMode
                ? (branding.site_logo_url || undefined)
                : (restaurantLogoUrl || branding.site_logo_url || undefined)}
              size={32}
            />
          {!isCollapsed && (
            <div className="flex flex-col min-w-0 overflow-hidden" style={{ animation: 'fadeIn 0.2s ease-out' }}>
              <span className="font-bold text-base tracking-tight whitespace-nowrap" style={{ color: isAdminMode ? 'white' : 'hsl(var(--foreground))' }}>
                {isAdminMode ? siteTitle : restaurantName}
              </span>
              <span className="text-xs whitespace-nowrap truncate" style={{ color: isAdminMode ? 'rgba(255,255,255,0.5)' : 'hsl(var(--muted-foreground))' }}>
                {isAdminMode ? t('admin.adminPanel', 'Admin Panel') : userRole}
              </span>
            </div>
          )}
        </div>
      </div>

      {impersonatingName && onExitImpersonation && (
        <div
          className="shrink-0"
          style={{ borderBottom: `1px solid hsl(var(--border))`, backgroundColor: 'hsl(25 95% 53% / 0.12)' }}
        >
          {isCollapsed ? (
            <div className="flex justify-center py-2">
              <button
                onClick={onExitImpersonation}
                disabled={exitingImpersonation}
                title={`${t('admin.impersonating', 'Impersonating')}: ${impersonatingName} — ${t('common.exit', 'Exit')}`}
                className="w-9 h-9 flex items-center justify-center rounded-lg transition-all"
                style={{ backgroundColor: 'hsl(var(--warning))', color: 'white', opacity: exitingImpersonation ? 0.7 : 1 }}
              >
                {exitingImpersonation ? <Loader2 size={14} className="animate-spin" /> : <LogIn size={14} />}
              </button>
            </div>
          ) : (
            <div className="px-3 py-2 flex flex-col gap-1.5">
              <p className="text-xs font-semibold truncate" style={{ color: 'hsl(var(--warning))' }}>
                {t('admin.impersonating', 'Impersonating')}: {impersonatingName}
              </p>
              <button
                onClick={onExitImpersonation}
                disabled={exitingImpersonation}
                className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-all"
                style={{ backgroundColor: 'hsl(var(--warning))', color: 'white', opacity: exitingImpersonation ? 0.7 : 1 }}
              >
                {exitingImpersonation ? <Loader2 size={11} className="animate-spin" /> : <LogIn size={11} />}
                {t('admin.exitImpersonation', 'Exit & Return to Admin')}
              </button>
            </div>
          )}
        </div>
      )}

      {!isCollapsed && onToggleAdminMode && (
        <div className="px-3 py-2" style={{ borderBottom: `1px solid ${isAdminMode ? 'rgba(255,255,255,0.1)' : 'hsl(var(--border))'}` }}>
          {isAdminMode ? (
            <Link
              href="/admin/restaurants"
              className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-semibold transition-all"
              style={{ backgroundColor: 'rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.8)' }}
            >
              <Shield size={13} />
              {t('admin.switchToRestaurant', 'Switch to Restaurant')}
            </Link>
          ) : (
            <button
              onClick={onToggleAdminMode}
              className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-semibold transition-all"
              style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
            >
              <Shield size={13} />
              {t('admin.switchToAdmin', 'Switch to Admin Panel')}
            </button>
          )}
        </div>
      )}

      <nav className="flex-1 overflow-y-auto overflow-x-hidden scrollbar-thin py-3 px-2">
        {navGroups.map((group) => (
          <div key={group.label} className="mb-4">
            {!isCollapsed && (
              <p className="section-label px-3 mb-1.5" style={{ color: isAdminMode ? 'rgba(255,255,255,0.35)' : undefined }}>{group.label}</p>
            )}
            {isCollapsed && <div className="mb-1 mt-1 mx-3 border-t" style={{ borderColor: isAdminMode ? 'rgba(255,255,255,0.1)' : 'hsl(var(--border))' }} />}
            <ul className="space-y-0.5">
              {group.items.map((item) => {
                const isActive = pathname === item.href || (item.href !== '/ai-agent-config' && pathname?.startsWith(item.href + '/'));
                const activeStyle = isAdminMode
                  ? { backgroundColor: 'rgba(255,255,255,0.12)', color: 'white' }
                  : { backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' };
                const inactiveStyle = { color: isAdminMode ? 'rgba(255,255,255,0.6)' : 'hsl(var(--foreground-secondary))' };
                const hoverStyle = isAdminMode ? 'hover:bg-white/10' : '';

                if (item.disabled) return null;

                return (
                  <li key={item.href}>
                    <Link
                      href={item.href}
                      className={`sidebar-nav-item flex flex-row items-center gap-3 ${isCollapsed ? 'justify-center !px-0 mx-auto w-10 h-10' : ''} ${hoverStyle}`}
                      style={isActive ? activeStyle : inactiveStyle}
                      title={isCollapsed ? item.label : undefined}
                    >
                      <span className="shrink-0">{item.icon}</span>
                      {!isCollapsed && <span className="truncate flex-1">{item.label}</span>}
                      {!isCollapsed && item.badge !== undefined && item.badge > 0 && (
                        <span className={`text-xs px-1.5 py-0.5 rounded-full font-semibold ${getBadgeClass(item.badgeVariant)}`}>{item.badge}</span>
                      )}
                      {isCollapsed && item.badge !== undefined && item.badge > 0 && (
                        <span className={`absolute top-0 right-0 text-xs w-4 h-4 flex items-center justify-center rounded-full font-bold ${getBadgeClass(item.badgeVariant)}`} style={{ fontSize: '10px' }}>
                          {item.badge}
                        </span>
                      )}
                    </Link>
                  </li>
                );
              })}
            </ul>
          </div>
        ))}
      </nav>

      {!isCollapsed && (
        <div className="px-3 py-3 shrink-0 relative" ref={profileMenuRef} style={{ borderTop: `1px solid ${isAdminMode ? 'rgba(255,255,255,0.1)' : 'hsl(var(--border))'}` }}>
          <button
            onClick={() => setShowProfileMenu(!showProfileMenu)}
            className="w-full flex items-center gap-2.5 px-2 py-2 rounded-lg transition-colors hover:bg-black/5"
            style={isAdminMode ? { color: 'white' } : {}}
          >
            <div className="w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold shrink-0" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
              {userInitials}
            </div>
            <div className="flex-1 min-w-0 text-left">
              <p className="text-xs font-semibold truncate" style={{ color: isAdminMode ? 'white' : 'hsl(var(--foreground))' }}>{userName}</p>
              <p className="text-xs truncate" style={{ color: isAdminMode ? 'rgba(255,255,255,0.4)' : 'hsl(var(--muted-foreground))' }}>{userRole}</p>
            </div>
            <ChevronUp size={14} className="shrink-0 transition-transform" style={{ color: isAdminMode ? 'rgba(255,255,255,0.4)' : 'hsl(var(--muted-foreground))', transform: showProfileMenu ? 'rotate(0deg)' : 'rotate(180deg)' }} />
          </button>

          {showProfileMenu && (
            <div
              className="absolute bottom-full left-3 right-3 mb-2 rounded-xl shadow-xl z-50 fade-in"
              style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))', boxShadow: 'var(--shadow-xl)' }}
            >
              <div className="px-4 py-3" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                <p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{userName}</p>
                {userEmail && <p className="text-xs mt-0.5 truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>{userEmail}</p>}
              </div>

              {!isAdminRole && (
                <div className="px-3 py-2" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                  <div className="flex items-center gap-2.5 px-2 py-2 rounded-lg" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
                    <div className="w-7 h-7 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--primary))', color: 'white' }}>
                      <Zap size={13} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-bold" style={{ color: 'hsl(var(--primary))' }}>{t('billing.proPlan', 'Pro Plan')}</p>
                      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.active', 'Active')}</p>
                    </div>
                  </div>
                </div>
              )}

              <div className="py-1">
                <Link
                  href={isAdminMode ? '/admin/branding' : '/restaurant-settings'}
                  className="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-black/5 text-sm"
                  style={{ color: 'hsl(var(--foreground))' }}
                  onClick={() => setShowProfileMenu(false)}
                >
                  <Settings size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  {t('nav.settings', 'Settings')}
                </Link>
                <Link href={isAdminMode ? '/admin/change-password' : '/change-password'} className="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-black/5 text-sm" style={{ color: 'hsl(var(--foreground))' }} onClick={() => setShowProfileMenu(false)}>
                  <KeyRound size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  {t('settings.changePassword', 'Change Password')}
                </Link>
                <a href="https://restroagent.com" target="_blank" rel="noopener noreferrer" className="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-black/5 text-sm" style={{ color: 'hsl(var(--foreground))' }}>
                  <ExternalLink size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  {t('common.website', 'Website')}
                </a>
                <LanguageSwitcher variant="sidebar" />
              </div>

              <div className="py-1" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                <button onClick={() => { setShowProfileMenu(false); signOut(); }} className="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-black/5 text-sm" style={{ color: 'hsl(var(--danger))' }}>
                  <LogOut size={15} />
                  {t('auth.logOut', 'Log Out')}
                </button>
              </div>
            </div>
          )}
        </div>
      )}
    </aside>
  );
}
