import { useState, useEffect, useRef, useCallback } from 'react'

interface DateRange {
  year: number
  month: number
  count: number
}

interface Section {
  key: string
  label: string
  year: number
  month: number
}

interface Props {
  ranges: DateRange[]
  sections: Section[]
  onJumpToDate?: (year: number, month: number) => void
}

const MONTH_SHORT = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

export default function TimelineScrubber({ ranges, sections, onJumpToDate }: Props) {
  const [activeKey, setActiveKey] = useState<string>('')
  const observerRef = useRef<IntersectionObserver | null>(null)

  // Track which section is in view
  useEffect(() => {
    if (observerRef.current) observerRef.current.disconnect()

    const observer = new IntersectionObserver(
      (entries) => {
        // Find the topmost visible section
        let topEntry: IntersectionObserverEntry | null = null
        for (const entry of entries) {
          if (entry.isIntersecting) {
            if (!topEntry || entry.boundingClientRect.top < topEntry.boundingClientRect.top) {
              topEntry = entry
            }
          }
        }
        if (topEntry) {
          const id = topEntry.target.id
          const key = id.replace('gallery-section-', '')
          setActiveKey(key)
        }
      },
      { rootMargin: '-10% 0px -70% 0px', threshold: 0 }
    )

    observerRef.current = observer

    // Observe all section headers
    for (const section of sections) {
      const el = document.getElementById(`gallery-section-${section.key}`)
      if (el) observer.observe(el)
    }

    return () => observer.disconnect()
  }, [sections])

  const scrollTo = useCallback((key: string, year: number, month: number) => {
    // Try exact key first, then prefix match (daily sections use YYYY-MM-DD keys)
    let el = document.getElementById(`gallery-section-${key}`)
    if (!el) {
      // Find first section element that starts with this month prefix
      const prefix = `${year}-${String(month).padStart(2, '0')}`
      for (const section of sections) {
        if (section.key.startsWith(prefix)) {
          el = document.getElementById(`gallery-section-${section.key}`)
          if (el) break
        }
      }
    }
    if (el) {
      el.scrollIntoView({ behavior: 'smooth', block: 'start' })
    } else if (onJumpToDate) {
      // Section not in DOM yet (not loaded via infinite scroll) — ask parent to load from this date
      onJumpToDate(year, month)
    }
  }, [onJumpToDate, sections])

  // Decide compact mode: if >24 entries, show years + quarters only
  const compact = ranges.length > 24

  // Group ranges by year
  const years = new Map<number, DateRange[]>()
  for (const r of ranges) {
    if (!years.has(r.year)) years.set(r.year, [])
    years.get(r.year)!.push(r)
  }

  return (
    <div className="hidden md:flex fixed right-2 top-16 bottom-4 z-30 flex-col items-end gap-0.5 overflow-y-auto scrollbar-thin pr-1">
      {Array.from(years.entries()).map(([year, months]) => (
        <div key={year} className="flex flex-col items-end">
          {/* Year label */}
          <button
            type="button"
            className={`text-xs font-bold px-1.5 py-0.5 rounded transition-colors ${
              months.some(m => activeKey.startsWith(`${m.year}-${String(m.month).padStart(2, '0')}`))
                ? 'text-primary'
                : 'text-muted-foreground hover:text-foreground'
            }`}
            onClick={() => {
              const firstMonth = months[0]
              scrollTo(
                `${firstMonth.year}-${String(firstMonth.month).padStart(2, '0')}`,
                firstMonth.year,
                firstMonth.month
              )
            }}
          >
            {year}
          </button>

          {/* Month labels */}
          {!compact && months.map(m => {
            const key = `${m.year}-${String(m.month).padStart(2, '0')}`
            const isActive = activeKey.startsWith(key)
            return (
              <button
                key={key}
                type="button"
                className={`text-[10px] px-1.5 py-0.5 rounded transition-colors ${
                  isActive
                    ? 'text-primary font-semibold bg-primary/10'
                    : 'text-muted-foreground hover:text-foreground'
                }`}
                onClick={() => scrollTo(key, m.year, m.month)}
              >
                {MONTH_SHORT[m.month]}
              </button>
            )
          })}

          {/* Compact: show quarters */}
          {compact && (() => {
            const quarters = new Map<number, DateRange[]>()
            for (const m of months) {
              const q = Math.ceil(m.month / 3)
              if (!quarters.has(q)) quarters.set(q, [])
              quarters.get(q)!.push(m)
            }
            return Array.from(quarters.entries()).map(([q, qMonths]) => {
              const firstMonth = qMonths[0]
              const key = `${firstMonth.year}-${String(firstMonth.month).padStart(2, '0')}`
              const isActive = qMonths.some(
                m => activeKey.startsWith(`${m.year}-${String(m.month).padStart(2, '0')}`)
              )
              return (
                <button
                  key={`${year}-Q${q}`}
                  type="button"
                  className={`text-[10px] px-1.5 py-0.5 rounded transition-colors ${
                    isActive
                      ? 'text-primary font-semibold bg-primary/10'
                      : 'text-muted-foreground hover:text-foreground'
                  }`}
                  onClick={() => scrollTo(key, firstMonth.year, firstMonth.month)}
                >
                  Q{q}
                </button>
              )
            })
          })()}
        </div>
      ))}
    </div>
  )
}
