import { useCallback, useEffect, useRef, useState } from 'react'
import { Link, useLocation } from 'react-router-dom'
import type { LucideIcon } from 'lucide-react'
import {
  LayoutGrid, Clock, AlertTriangle, GitBranch, Layers, Code2, Wand2,
  ListChecks, Download, BarChart3, Rocket, BookOpen, MessageSquare,
  Settings, Pin, PinOff,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { useUserPreferencesStore } from '@/store/userPreferencesStore'
import { sidebarApi } from '@/api'
import type { SidebarStatsResponse } from '@/api/sidebar'
import { prefetchForRoute } from '@/lib/routePrefetch'

/* ── Types ──────────────────────────────────────────── */

interface NavSubItem {
  href: string
  label: string
  count?: number
}

interface NavEntry {
  href: string
  icon: LucideIcon
  label: string
  shortLabel: string
  badge?: number
  matchPaths?: string[]
  children?: NavSubItem[]
}

interface NavSection {
  title: string
  items: NavEntry[]
}

/* ── Sidebar component ──────────────────────────────── */

export function Sidebar() {
  const location = useLocation()
  const sidebarPinned = useUserPreferencesStore(s => s.sidebarPinned)
  const toggleSidebarPinned = useUserPreferencesStore(s => s.toggleSidebarPinned)

  const [stats, setStats] = useState<SidebarStatsResponse | null>(null)
  const [flyoutIndex, setFlyoutIndex] = useState<string | null>(null)
  const flyoutTimeout = useRef<ReturnType<typeof setTimeout> | null>(null)
  const sidebarRef = useRef<HTMLElement>(null)

  /* ── Stats fetching ───────────────────────────────── */

  const refreshStats = useCallback(() => {
    sidebarApi.getStats().then(setStats).catch(() => {})
  }, [])

  useEffect(() => { refreshStats() }, [location.pathname, refreshStats])

  useEffect(() => {
    window.addEventListener('session-changed', refreshStats)
    return () => window.removeEventListener('session-changed', refreshStats)
  }, [refreshStats])

  /* ── Navigation data ──────────────────────────────── */

  const sections: NavSection[] = [
    {
      title: 'RESOLVE',
      items: [
        { href: '/', icon: LayoutGrid, label: 'Dashboard', shortLabel: 'Dash' },
        { href: '/sessions', icon: Clock, label: 'Active Sessions', shortLabel: 'Sessions', badge: stats?.active_count || undefined, matchPaths: ['/sessions'] },
        { href: '/escalations', icon: AlertTriangle, label: 'Escalations', shortLabel: 'Escal', badge: stats?.escalation_count || undefined },
      ],
    },
    {
      title: 'KNOWLEDGE',
      items: [
        {
          href: '/trees', icon: GitBranch, label: 'Flows', shortLabel: 'Flows',
          badge: stats?.tree_counts.total || undefined,
          matchPaths: ['/trees', '/flows', '/my-trees'],
          children: [
            { href: '/trees', label: 'All Flows' },
            { href: '/trees?type=troubleshooting', label: 'Troubleshooting', count: stats?.tree_counts.troubleshooting || undefined },
            { href: '/trees?type=procedural', label: 'Projects', count: stats?.tree_counts.procedural || undefined },
            { href: '/trees?type=maintenance', label: 'Maintenance', count: stats?.tree_counts.maintenance || undefined },
          ],
        },
        { href: '/step-library', icon: Layers, label: 'Step Library', shortLabel: 'Steps' },
        { href: '/scripts', icon: Code2, label: 'Scripts', shortLabel: 'Scripts' },
        { href: '/script-builder', icon: Wand2, label: 'Script Builder', shortLabel: 'Builder' },
        { href: '/review-queue', icon: ListChecks, label: 'Review Queue', shortLabel: 'Review' },
      ],
    },
    {
      title: 'INSIGHTS',
      items: [
        { href: '/shares', icon: Download, label: 'Exports', shortLabel: 'Export' },
        { href: '/analytics', icon: BarChart3, label: 'Analytics', shortLabel: 'Stats' },
        { href: '/analytics/flowpilot', icon: Rocket, label: 'FlowPilot Analytics', shortLabel: 'FPilot' },
      ],
    },
  ]

  const footerItems: NavEntry[] = [
    { href: '/guides', icon: BookOpen, label: 'User Guides', shortLabel: 'Guides' },
    { href: '/feedback', icon: MessageSquare, label: 'Feedback', shortLabel: 'Feedbk' },
    { href: '/account', icon: Settings, label: 'Account', shortLabel: 'Acct' },
  ]

  /* ── Active detection ─────────────────────────────── */

  const isActive = (item: NavEntry) => {
    if (item.matchPaths) return item.matchPaths.some(p => location.pathname.startsWith(p))
    if (item.href === '/') return location.pathname === '/'
    return location.pathname.startsWith(item.href)
  }

  const isChildActive = (child: NavSubItem) => {
    const fullPath = location.pathname + location.search
    return fullPath === child.href || fullPath.startsWith(child.href + '&')
  }

  /* ── Flyout management ────────────────────────────── */

  const openFlyout = (key: string) => {
    if (flyoutTimeout.current) clearTimeout(flyoutTimeout.current)
    setFlyoutIndex(key)
  }

  const closeFlyout = () => {
    flyoutTimeout.current = setTimeout(() => setFlyoutIndex(null), 120)
  }

  const keepFlyout = () => {
    if (flyoutTimeout.current) clearTimeout(flyoutTimeout.current)
  }

  /* Close flyout on Escape */
  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setFlyoutIndex(null)
    }
    document.addEventListener('keydown', handleKey)
    return () => document.removeEventListener('keydown', handleKey)
  }, [])

  /* ── Wheel forwarding (when sidebar can't scroll) ── */

  const handleWheel = (e: React.WheelEvent<HTMLElement>) => {
    const el = e.currentTarget
    const canScroll = el.scrollHeight > el.clientHeight
    const atTop = el.scrollTop <= 0
    const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1
    if (!canScroll || (e.deltaY < 0 && atTop) || (e.deltaY > 0 && atBottom)) {
      const main = document.querySelector('.main-content') as HTMLElement | null
      if (main) { main.scrollTop += e.deltaY; e.preventDefault() }
    }
  }

  /* ── Render helpers ───────────────────────────────── */

  const renderRailItem = (item: NavEntry, key: string) => {
    const active = isActive(item)
    const Icon = item.icon
    const hasChildren = item.children && item.children.length > 0

    return (
      <div
        key={key}
        className="relative"
        onMouseEnter={() => hasChildren && !sidebarPinned ? openFlyout(key) : undefined}
        onMouseLeave={() => hasChildren && !sidebarPinned ? closeFlyout() : undefined}
      >
        <Link
          to={item.href}
          onMouseEnter={() => prefetchForRoute(item.href)}
          onFocus={() => hasChildren && !sidebarPinned ? openFlyout(key) : undefined}
          onBlur={() => hasChildren && !sidebarPinned ? closeFlyout() : undefined}
          className={cn(
            'group relative flex flex-col items-center justify-center rounded-lg px-1 py-2 transition-all duration-150',
            active
              ? 'bg-[rgba(34,211,238,0.10)] text-[#67e8f9]'
              : 'text-[#6b7280] hover:text-[#848b9b]'
          )}
          title={item.label}
        >
          <span className="relative">
            <Icon size={20} className={active ? 'opacity-100' : 'opacity-60 group-hover:opacity-85'} />
            {item.badge !== undefined && item.badge > 0 && (
              <span className="absolute -right-1.5 -top-1.5 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-[#22d3ee] px-1 text-[0.5rem] font-bold text-[#0c0d10]">
                {item.badge > 99 ? '99+' : item.badge}
              </span>
            )}
          </span>
          <span className="mt-1 text-[0.5625rem] font-mono leading-tight truncate max-w-[60px]">
            {item.shortLabel}
          </span>
        </Link>

        {/* Flyout panel (icon rail only) */}
        {hasChildren && !sidebarPinned && flyoutIndex === key && (
          <div
            className="fixed z-50 ml-1"
            style={{
              left: '72px',
              top: sidebarRef.current
                ? (() => {
                    const itemEl = sidebarRef.current.querySelector(`[data-flyout-key="${key}"]`)
                    if (itemEl) {
                      const rect = itemEl.getBoundingClientRect()
                      return `${rect.top}px`
                    }
                    return '0px'
                  })()
                : '0px',
              maxHeight: '70vh',
              overflowY: 'auto',
            }}
            onMouseEnter={keepFlyout}
            onMouseLeave={closeFlyout}
          >
            <div
              className="w-[220px] rounded-lg p-2 animate-fade-in"
              style={{
                background: '#14161d',
                border: '1px solid #1e2130',
                boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
              }}
            >
              {item.children!.map(child => (
                <Link
                  key={child.href}
                  to={child.href}
                  className={cn(
                    'flex items-center justify-between rounded-md px-3 py-2 text-[0.8125rem] transition-colors',
                    isChildActive(child)
                      ? 'bg-[rgba(34,211,238,0.10)] text-[#67e8f9]'
                      : 'text-[#848b9b] hover:bg-[#191c25] hover:text-[#e2e5eb]'
                  )}
                >
                  <span>{child.label}</span>
                  {child.count !== undefined && (
                    <span className="text-[0.6875rem] font-mono text-[#4f5666]">{child.count}</span>
                  )}
                </Link>
              ))}
            </div>
          </div>
        )}
      </div>
    )
  }

  const renderPinnedItem = (item: NavEntry, key: string) => {
    const active = isActive(item)
    const Icon = item.icon
    const fullPath = location.pathname + location.search
    const activeChild = item.children?.find(c => fullPath === c.href || fullPath.startsWith(c.href + '&'))
    const isParentDimmed = !!activeChild && active

    return (
      <div key={key} className="group/nav">
        <Link
          to={item.href}
          onMouseEnter={() => prefetchForRoute(item.href)}
          className={cn(
            'group relative flex items-center gap-3 rounded-lg px-3 py-2 text-[0.8125rem] font-medium transition-all duration-150',
            active
              ? isParentDimmed
                ? 'bg-[rgba(34,211,238,0.05)] text-[#e2e5eb]/70'
                : 'bg-[rgba(34,211,238,0.10)] text-[#e2e5eb]'
              : 'text-[#848b9b] hover:bg-[#191c25] hover:text-[#e2e5eb]'
          )}
        >
          {active && !isParentDimmed && (
            <div
              className="absolute left-0 top-1/2 h-6 w-[3px] -translate-y-1/2"
              style={{ background: '#22d3ee', borderRadius: '0 3px 3px 0' }}
            />
          )}
          <Icon size={18} className={cn('shrink-0', active ? 'opacity-100' : 'opacity-70')} />
          <span className="truncate">{item.label}</span>
          {item.badge !== undefined && item.badge > 0 && (
            <span className="ml-auto shrink-0 rounded-full px-2 text-[0.6875rem] font-mono text-[#4f5666]"
              style={{ background: '#14161d', border: '1px solid #1e2130' }}>
              {item.badge}
            </span>
          )}
        </Link>

        {/* Sub-items for pinned mode */}
        {item.children && item.children.length > 0 && (
          <div className={cn(
            'mt-0.5 space-y-0.5 overflow-hidden transition-all duration-200',
            active || activeChild
              ? 'max-h-40 opacity-100'
              : 'max-h-0 opacity-0 group-hover/nav:max-h-40 group-hover/nav:opacity-100'
          )}>
            {item.children.map(child => {
              const childActive = isChildActive(child)
              return (
                <Link
                  key={child.href}
                  to={child.href}
                  className={cn(
                    'flex items-center gap-2 rounded-lg pl-9 pr-3 py-1.5 text-[0.8125rem] font-medium transition-colors',
                    childActive
                      ? 'bg-[rgba(34,211,238,0.10)] text-[#e2e5eb]'
                      : 'text-[#848b9b] hover:bg-[#191c25] hover:text-[#e2e5eb]'
                  )}
                >
                  <span className="truncate">{child.label}</span>
                  {child.count !== undefined && (
                    <span className="ml-auto shrink-0 rounded-full px-2 text-[0.6875rem] font-mono text-[#4f5666]"
                      style={{ background: '#14161d', border: '1px solid #1e2130' }}>
                      {child.count}
                    </span>
                  )}
                </Link>
              )
            })}
          </div>
        )}
      </div>
    )
  }

  /* ── Flyout positioning: use data attribute for lookup ── */

  const renderRailItemWithRef = (item: NavEntry, key: string) => {
    return (
      <div key={key} data-flyout-key={key}>
        {renderRailItem(item, key + '-inner')}
      </div>
    )
  }

  /* ── Main render ──────────────────────────────────── */

  if (sidebarPinned) {
    return (
      <nav
        ref={sidebarRef}
        className="sidebar flex flex-col"
        style={{ background: '#0f1118', borderRight: '1px solid #1e2130' }}
        onWheel={handleWheel}
      >
        {/* Pinned sidebar content */}
        <div className="px-3 py-2 space-y-0.5">
          {sections.map((section, si) => (
            <div key={section.title}>
              {si > 0 && (
                <div className="font-mono text-[0.5625rem] uppercase tracking-[0.12em] text-[#4f5666] px-3 pt-3 pb-1">
                  {section.title}
                </div>
              )}
              {section.items.map((item, ii) => renderPinnedItem(item, `${si}-${ii}`))}
            </div>
          ))}
        </div>

        <div className="flex-1" />

        {/* Footer */}
        <div className="px-3 py-2 space-y-0.5" style={{ borderTop: '1px solid #1e2130' }}>
          {footerItems.map((item, i) => renderPinnedItem(item, `footer-${i}`))}
          <button
            type="button"
            onClick={toggleSidebarPinned}
            className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-[0.8125rem] font-medium text-[#848b9b] hover:bg-[#191c25] hover:text-[#e2e5eb] transition-colors"
            title="Unpin sidebar"
          >
            <PinOff size={18} className="shrink-0" />
            <span>Unpin</span>
          </button>
        </div>
      </nav>
    )
  }

  /* Icon Rail (default) */
  return (
    <nav
      ref={sidebarRef}
      className="sidebar flex flex-col items-center"
      style={{ background: '#0f1118', borderRight: '1px solid #1e2130' }}
      onWheel={handleWheel}
    >
      {/* Nav sections */}
      <div className="flex flex-col items-center w-full px-1.5 py-2 space-y-0.5">
        {sections.map((section, si) => (
          <div key={section.title} className="w-full">
            {si > 0 && (
              <div className="mx-3 my-2" style={{ borderTop: '1px solid #1e2130' }} />
            )}
            {section.items.map((item, ii) => renderRailItemWithRef(item, `${si}-${ii}`))}
          </div>
        ))}
      </div>

      <div className="flex-1" />

      {/* Footer */}
      <div className="flex flex-col items-center w-full px-1.5 py-2 space-y-0.5" style={{ borderTop: '1px solid #1e2130' }}>
        {footerItems.map((item, i) => (
          <div key={`footer-${i}`} data-flyout-key={`footer-${i}`}>
            {renderRailItem(item, `footer-${i}-inner`)}
          </div>
        ))}
        <button
          type="button"
          onClick={toggleSidebarPinned}
          className="flex flex-col items-center justify-center rounded-lg px-1 py-2 text-[#6b7280] hover:text-[#848b9b] transition-colors"
          title="Pin sidebar"
        >
          <Pin size={18} className="opacity-60 hover:opacity-85" />
          <span className="mt-1 text-[0.5625rem] font-mono leading-tight">Pin</span>
        </button>
      </div>
    </nav>
  )
}
