import { safeHttpUrl } from '@overdeck/deck-ui'
import { useEffect, useState } from 'react'
import { fetchCollectorItems, fetchCollectorState } from '../lib/collector-client'
import { sidebarBadgesFromState, type SidebarBadge } from '../lib/sidebar-badges'
import { SIDEBAR_SECTIONS, type SidebarSection } from '../lib/sidebar-nav'
import { ThemeToggle } from './ThemeToggle'

const BADGE_POLL_MS = 15_000

export interface SidebarProps {
  activePath: string
  onNavigate?: () => void
}

const LIVE_BADGE_ROUTES = new Set(['/inbox', '/decisions', '/bots', '/agents'])

function mergeSections(sections: SidebarSection[], badges: Record<string, SidebarBadge | undefined>): SidebarSection[] {
  return sections.map((section) => ({
    ...section,
    items: section.items.map((item) => {
      if (!LIVE_BADGE_ROUTES.has(item.href)) return item
      const live = badges[item.href]
      if (!live) {
        const { badge: _badge, hot: _hot, ...rest } = item
        return rest
      }
      return { ...item, badge: live.label, hot: live.hot ?? item.hot }
    }),
  }))
}

export function Sidebar({ activePath, onNavigate }: SidebarProps) {
  const [sections, setSections] = useState(() => mergeSections(SIDEBAR_SECTIONS, {}))

  useEffect(() => {
    let cancelled = false

    async function refresh() {
      try {
        const [state, itemsResponse] = await Promise.all([fetchCollectorState(), fetchCollectorItems()])
        if (!cancelled) setSections(mergeSections(SIDEBAR_SECTIONS, sidebarBadgesFromState(state, itemsResponse.items)))
      } catch {
        if (!cancelled) setSections(mergeSections(SIDEBAR_SECTIONS, {}))
      }
    }

    void refresh()
    const timer = window.setInterval(() => void refresh(), BADGE_POLL_MS)
    return () => {
      cancelled = true
      window.clearInterval(timer)
    }
  }, [])

  return (
    <div className="flex h-full w-full flex-col bg-bg p-2.5 md:w-[198px]">
      <div className="flex items-center gap-2 px-2.5 pb-4 pt-0.5 text-sm font-bold text-fg">
        <i className="block h-[22px] w-[22px] rounded-md bg-gradient-to-br from-accent to-info" />
        Overdeck
      </div>
      {sections.map((section, i) => (
        <div key={section.title ?? `section-${i}`}>
          {section.title && (
            <div className="px-2.5 pb-1.5 pt-3.5 text-[10px] uppercase tracking-[0.14em] text-fg-subtle">
              {section.title}
            </div>
          )}
          {section.items.map((item) => {
            const isActive = item.href === activePath
            return (
              <a
                key={item.href}
                href={safeHttpUrl(item.href)}
                onClick={onNavigate}
                aria-current={isActive ? 'page' : undefined}
                className={
                  'mb-0.5 flex items-center justify-between rounded-lg px-2.5 py-1.5 text-[13px] no-underline ' +
                  (isActive ? 'bg-surface-raised font-semibold text-fg' : 'text-fg-muted')
                }
              >
                <span>{item.label}</span>
                {item.badge && (
                  <span
                    className={
                      'rounded-[9px] px-1.5 text-[11px] leading-[18px] ' +
                      (item.hot ? 'bg-danger/20 text-danger' : 'bg-surface-raised text-fg-muted')
                    }
                  >
                    {item.badge}
                  </span>
                )}
              </a>
            )
          })}
        </div>
      ))}
      <ThemeToggle />
    </div>
  )
}
