/**
 * BoostMedia AI Content Generator Admin - Sidebar Component
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useMemo, useState, useEffect, useRef } from 'react'
import { NavLink } from 'react-router-dom'
import {
  LayoutDashboard,
  FileText,
  Sparkles,
  Briefcase,
  List,
  Link2,
  Newspaper,
  ClipboardList,
  Coins,
  Download,
  Settings,
  Activity,
} from 'lucide-react'
import type { ReactNode } from 'react'
import { Badge } from '../common'
import { useUpdateCheck } from '../../hooks/useUpdateCheck'
import { useOnboarding } from '../../hooks/useOnboarding'
import { PingDot } from '../onboarding/PingDot'
import { t } from '../../lib/i18n'
import { endpoints } from '../../api/client'
import appIconUrl from '../../assets/app-icon.png'

interface MenuItem {
  id: string
  label: string
  icon: ReactNode
  path: string
  badge?: number
  disabled?: boolean
}

export function Sidebar() {
  const { updateAvailable } = useUpdateCheck()
  const { needsSetup, isSetupComplete } = useOnboarding()
  const [activeJobCount, setActiveJobCount] = useState(0)
  const mountedRef = useRef(true)

  const pingMap: Record<string, boolean> = {
    '/usage': needsSetup.usage,
    '/post-types': needsSetup.contentTypes,
    '/links': needsSetup.links,
    '/reporters': needsSetup.reporters,
    '/settings': needsSetup.settings,
  }

  useEffect(() => {
    mountedRef.current = true
    const check = async () => {
      try {
        const result = await endpoints.listJobs({ status: 'active', limit: 1 })
        if (mountedRef.current) setActiveJobCount(result?.data?.summary?.active_count || 0)
      } catch { /* ignore */ }
    }
    check()
    const interval = setInterval(check, 30000)
    return () => { mountedRef.current = false; clearInterval(interval) }
  }, [])

  const debugMode = Boolean((window as any).bmaiSettings?.debugMode)

  const menuItems: MenuItem[] = useMemo(() => {
    const items: MenuItem[] = [
      { id: 'dashboard', label: t('Dashboard'), icon: <LayoutDashboard className="w-5 h-5" />, path: '/' },
      { id: 'usage', label: t('Usage & Costs'), icon: <Coins className="w-5 h-5" />, path: '/usage' },
      { id: 'post-types', label: t('Content Types'), icon: <FileText className="w-5 h-5" />, path: '/post-types' },
      { id: 'links', label: t('Links'), icon: <Link2 className="w-5 h-5" />, path: '/links' },
      { id: 'reporters', label: t('Reporters'), icon: <Newspaper className="w-5 h-5" />, path: '/reporters' },
      { id: 'plans', label: t('Content Plans'), icon: <Briefcase className="w-5 h-5" />, path: '/plans' },
      { id: 'generate', label: t('Create Content'), icon: <Sparkles className="w-5 h-5" />, path: '/generate' },
      { id: 'jobs', label: t('Jobs'), icon: <Activity className="w-5 h-5" />, path: '/jobs', badge: activeJobCount > 0 ? activeJobCount : undefined },
      { id: 'generated', label: t('Generated Content'), icon: <List className="w-5 h-5" />, path: '/generated' },
      { id: 'updates', label: t('Updates'), icon: <Download className="w-5 h-5" />, path: '/updates' },
      { id: 'settings', label: t('Settings'), icon: <Settings className="w-5 h-5" />, path: '/settings' },
    ]
    if (debugMode) {
      items.push({ id: 'logs', label: t('Logs'), icon: <ClipboardList className="w-5 h-5" />, path: '/logs' })
    }
    return items
  }, [activeJobCount, debugMode])

  return (
    <aside className="w-64 min-w-64 bg-white border-s border-bc-gray-200 h-screen sticky top-0 flex flex-col shrink-0">
      {/* Logo */}
      <div className="p-4 border-b border-bc-gray-200">
        <div className="flex items-center gap-3">
          <img
            src={appIconUrl}
            alt="BoostMedia AI Content Generator"
            className="w-10 h-10 rounded-bc"
          />
          <div>
            <h1 className="text-lg font-bold text-bc-gray-800">BoostMedia AI Content Generator</h1>
            <p className="text-xs text-bc-gray-500">{t('AI Content Creation')}</p>
          </div>
        </div>
      </div>

      {/* Navigation */}
      <nav className="flex-1 p-4 overflow-y-auto bc-scrollbar">
        <ul className="space-y-1">
          {menuItems.map((item) => {
            const showPing = !isSetupComplete && !!pingMap[item.path]
            const hasBadge = item.badge != null && item.badge > 0
            const hasUpdateDot = item.id === 'updates' && updateAvailable

            return (
              <li key={item.id}>
                {item.disabled ? (
                  <span
                    className="flex items-center gap-3 px-4 py-3 rounded-bc text-bc-gray-400 cursor-not-allowed"
                  >
                    {item.icon}
                    <span>{item.label}</span>
                    <Badge variant="default" className="ms-auto text-[10px]">{t('Coming Soon')}</Badge>
                  </span>
                ) : (
                  <NavLink
                    to={item.path}
                    className={({ isActive }) =>
                      `flex items-center gap-3 px-4 py-3 rounded-bc transition-colors ${
                        isActive
                          ? 'bg-bc-primary-light text-bc-primary font-semibold'
                          : 'text-bc-gray-600 hover:bg-bc-gray-50'
                      }`
                    }
                  >
                    {item.icon}
                    <span>{item.label}</span>
                    {(showPing || hasBadge || hasUpdateDot) && (
                      <div className="flex items-center gap-1.5 ms-auto">
                        {showPing && <PingDot visible={true} size="sm" />}
                        {hasBadge && <Badge variant="accent">{item.badge}</Badge>}
                        {hasUpdateDot && <span className="w-2.5 h-2.5 rounded-full bg-amber-500 animate-pulse" />}
                      </div>
                    )}
                  </NavLink>
                )}
              </li>
            )
          })}
        </ul>
      </nav>

      {/* Footer */}
      <div className="p-4 border-t border-bc-gray-200">
        <div className="text-xs text-bc-gray-500 text-center">
          <p>{t('Version')} {window.bmaiSettings?.version || '1.0.3'}</p>
          <p className="mt-1">© Boost Media LTD</p>
        </div>
      </div>
    </aside>
  )
}
