import { useState, useEffect } from 'react'
import { NavLink, useLocation, useNavigate } from 'react-router-dom'
import { useNavigationGuard } from '@/contexts/NavigationGuardContext'
import { 
  LayoutDashboard, 
  Users, 
  MessageSquare, 
  Settings, 
  BarChart3,
  Bot,
  Lock,
  Database,
  Send,
  Sparkles,
  Contact,
  FileText,
  Palette,
  Zap,
  Calendar,
  Building2,
  Download,
  LifeBuoy,
  X,
  ShoppingCart,
} from 'lucide-react'
import { useLicense } from '@/hooks/useLicense'
import { useUpdateCheck } from '@/hooks/useUpdateCheck'
import { FeedbackModal } from '../common/FeedbackModal'
import { LanguageSelector } from '../common/LanguageSelector'
import { t } from '@/lib/i18n'

interface NavItem {
  name: string
  href: string
  icon: React.ComponentType<{ className?: string }>
  feature?: string
}

interface SidebarProps {
  isMobileOpen?: boolean
  onMobileClose?: () => void
}

function getNavigation(): NavItem[] {
  return [
    { name: t('Dashboard'), href: '/', icon: LayoutDashboard },
    { name: t('Bots'), href: '/bots', icon: Bot },
    { name: t('Personalities'), href: '/personalities', icon: Sparkles },
    { name: t('Contact Lists'), href: '/contact-lists', icon: Contact },
    { name: t('Widgets'), href: '/widgets', icon: FileText, feature: 'widgets' },
    { name: t('Appearance Settings'), href: '/appearance-presets', icon: Palette },
    { name: t('Opening Messages'), href: '/opening-screen-presets', icon: MessageSquare },
    { name: t('Meetings'), href: '/meetings', icon: Calendar },
    ...((window as any).boostbotAdmin?.woocommerce_active ? [{ name: 'WooCommerce', href: '/woocommerce-settings', icon: ShoppingCart, feature: 'woocommerce_bundles' }] : []),
    { name: t('Leads'), href: '/leads', icon: Users, feature: 'leads_management' },
    { name: t('Conversations'), href: '/conversations', icon: MessageSquare },
    { name: t('Knowledge Base'), href: '/knowledge-base', icon: Database, feature: 'knowledge_base' },
    { name: t('Business Card'), href: '/brand-card', icon: Building2 },
    { name: t('Integrations'), href: '/integrations', icon: Send },
    { name: t('Analytics'), href: '/analytics', icon: BarChart3, feature: 'analytics' },
    { name: t('Usage & Costs'), href: '/usage', icon: Zap },
    { name: t('Settings'), href: '/settings', icon: Settings },
    ...((window as any).boostbotAdmin?.selfHosted ? [{ name: t('Updates'), href: '/updates', icon: Download }] : []),
    { name: t('Remote Support'), href: '/support', icon: LifeBuoy },
  ]
}

function GuardedNavLink({ to, children, className, ...props }: { to: string; children: React.ReactNode; className?: string; [key: string]: unknown }) {
  const { checkGuard, isBlocked } = useNavigationGuard()
  const navigate = useNavigate()
  const location = useLocation()

  const handleClick = (e: React.MouseEvent) => {
    if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
      return
    }
    if (location.pathname === to) return
    if (!isBlocked()) return
    e.preventDefault()
    checkGuard(() => navigate(to))
  }

  return (
    <NavLink to={to} onClick={handleClick} className={className} {...props}>
      {children}
    </NavLink>
  )
}

export function Sidebar({ isMobileOpen = false, onMobileClose }: SidebarProps) {
  const location = useLocation()
  const { isFeatureEnabled } = useLicense()
  const { updateAvailable } = useUpdateCheck()
  const [isFeedbackOpen, setIsFeedbackOpen] = useState(false)

  // Close mobile sidebar on route change
  useEffect(() => {
    onMobileClose?.()
  }, [location.pathname]) // eslint-disable-line react-hooks/exhaustive-deps

  const sidebarContent = (
    <>
      {/* Glow animation for updates */}
      <style>{`
        @keyframes updateGlow {
          0%, 100% { box-shadow: 0 0 4px rgba(59, 194, 208, 0.3); background-color: rgba(59, 194, 208, 0.08); }
          50% { box-shadow: 0 0 12px rgba(59, 194, 208, 0.5); background-color: rgba(59, 194, 208, 0.15); }
        }
        .update-glow {
          animation: updateGlow 2s ease-in-out infinite;
        }
        @keyframes dotPulse {
          0%, 100% { transform: scale(1); opacity: 1; }
          50% { transform: scale(1.3); opacity: 0.7; }
        }
        .update-dot {
          animation: dotPulse 2s ease-in-out infinite;
        }
      `}</style>

      {/* Logo */}
      <div className="h-16 flex items-center justify-center border-b border-gray-200 px-4">
        <Bot className="w-8 h-8 text-primary-500" />
        <span className="text-xl font-bold text-gray-900 ms-2">BoostBot</span>
        {/* Close button - mobile only (rendered inside mobile overlay) */}
        <button
          onClick={onMobileClose}
          className="lg:hidden ms-auto p-1.5 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100 transition-colors"
          type="button"
        >
          <X className="w-5 h-5" />
        </button>
      </div>

      {/* Language Selector */}
      <div className="px-4 py-2 border-b border-gray-200">
        <LanguageSelector />
      </div>
      
      {/* Navigation */}
      <nav className="flex-1 p-4 space-y-1 overflow-y-auto">
        {getNavigation().map((item) => {
          const isActive = location.pathname === item.href || 
            (item.href !== '/' && location.pathname.startsWith(item.href)) ||
            (item.href === '/woocommerce-settings' && location.pathname.startsWith('/woocommerce-presets'))
          const Icon = item.icon
          const isLocked = item.feature && !isFeatureEnabled(item.feature)
          const isUpdatesWithGlow = item.href === '/updates' && updateAvailable && !isActive
          
          return (
            <GuardedNavLink
              key={item.href}
              to={item.href}
              className={`
                flex items-center px-4 py-3 rounded-lg text-sm font-medium
                transition-colors duration-150
                ${isActive 
                  ? 'bg-primary-50 text-primary-600' 
                  : 'text-gray-600 hover:bg-gray-50'
                }
                ${isLocked ? 'opacity-60' : ''}
                ${isUpdatesWithGlow ? 'update-glow text-primary-600' : ''}
              `}
            >
              <Icon className="w-5 h-5 me-3" />
              <span className="flex-1">{item.name}</span>
              {isLocked && (
                <Lock className="w-4 h-4 text-gray-400" />
              )}
              {item.href === '/updates' && updateAvailable && (
                <span className="update-dot w-2.5 h-2.5 rounded-full bg-primary-500 flex-shrink-0" />
              )}
            </GuardedNavLink>
          )
        })}
      </nav>
      
      {/* Feedback Button */}
      <div className="p-4 border-t border-gray-200">
        <button
          onClick={() => setIsFeedbackOpen(true)}
          className="
            w-full flex items-center justify-center gap-2 px-4 py-3 
            bg-gradient-to-r from-primary-500 to-primary-600 
            text-white rounded-lg font-medium
            hover:from-primary-600 hover:to-primary-700
            transition-all duration-150
            shadow-sm hover:shadow-md
          "
        >
          <Send className="w-4 h-4" />
          <span>{t('Send Feedback')}</span>
        </button>
      </div>
      
      {/* Feedback Modal */}
      <FeedbackModal 
        isOpen={isFeedbackOpen} 
        onClose={() => setIsFeedbackOpen(false)} 
      />
    </>
  )

  return (
    <>
      {/* Desktop sidebar — always visible */}
      <aside className="hidden lg:flex w-56 bg-white border-e border-gray-200 flex-col shadow-sm">
        {sidebarContent}
      </aside>

      {/* Mobile sidebar — overlay */}
      <style>{`
        .boostbot-mobile-sidebar {
          position: absolute;
          top: 0; bottom: 0;
          inset-inline-start: 0;
          transition: transform 300ms ease-in-out;
        }
        .boostbot-mobile-sidebar.is-hidden {
          transform: translateX(-100%);
        }
        [dir="rtl"] .boostbot-mobile-sidebar.is-hidden {
          transform: translateX(100%);
        }
        .boostbot-mobile-sidebar.is-visible {
          transform: translateX(0);
        }
      `}</style>
      <div
        className={`
          fixed inset-0 z-40 lg:hidden
          transition-opacity duration-300
          ${isMobileOpen ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'}
        `}
      >
        {/* Backdrop */}
        <div
          className="absolute inset-0 bg-black/40"
          onClick={onMobileClose}
        />

        {/* Panel */}
        <aside
          className={`
            boostbot-mobile-sidebar
            w-72 max-w-[85vw] bg-white shadow-xl flex flex-col
            ${isMobileOpen ? 'is-visible' : 'is-hidden'}
          `}
        >
          {sidebarContent}
        </aside>
      </div>
    </>
  )
}
