import { useEffect, useState } from 'react'

interface SidebarStatsBarProps {
  resolved: number
  active: number
  /** Minutes from completed sessions today (server-computed) */
  completedMinutes: number
  /** Start times of currently active sessions (ISO strings) */
  activeSessionStartTimes: string[]
}

function formatDuration(totalSeconds: number): string {
  if (totalSeconds < 60) return `${totalSeconds}s`
  const totalMinutes = Math.floor(totalSeconds / 60)
  if (totalMinutes < 60) return `${totalMinutes}m`
  const h = Math.floor(totalMinutes / 60)
  const m = totalMinutes % 60
  return m > 0 ? `${h}h ${m}m` : `${h}h`
}

function parseUTCTimestamp(st: string): number {
  // Backend returns naive UTC timestamps without 'Z' suffix.
  // JS Date() treats bare strings as local time, so append Z to force UTC.
  return new Date(st.endsWith('Z') ? st : st + 'Z').getTime()
}

function calcActiveSeconds(startTimes: string[]): number {
  const now = Date.now()
  return startTimes.reduce((sum, st) => {
    const elapsed = Math.floor((now - parseUTCTimestamp(st)) / 1000)
    return sum + Math.max(0, elapsed)
  }, 0)
}

export function SidebarStatsBar({ resolved, active, completedMinutes, activeSessionStartTimes }: SidebarStatsBarProps) {
  const [liveSeconds, setLiveSeconds] = useState(() => calcActiveSeconds(activeSessionStartTimes))

  // Tick every second to keep the timer in sync with the session timer
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional: syncs derived state from props
    setLiveSeconds(calcActiveSeconds(activeSessionStartTimes))
    if (activeSessionStartTimes.length === 0) return
    const interval = setInterval(() => {
      setLiveSeconds(calcActiveSeconds(activeSessionStartTimes))
    }, 1000)
    return () => clearInterval(interval)
  }, [activeSessionStartTimes])

  const totalSeconds = (completedMinutes * 60) + liveSeconds

  return (
    <div
      className="flex gap-0.5 px-3 pt-2 pb-1"
      role="group"
      aria-label="Today's stats"
    >
      <div className="flex-1 rounded-md bg-[rgba(255,255,255,0.02)] px-1 py-1.5 text-center">
        <div
          className="font-mono text-sm font-semibold leading-none"
          style={{ color: '#34d399' }}
          aria-label={`${resolved} resolved today`}
        >
          {resolved}
        </div>
        <div className="mt-1 font-mono text-[7px] uppercase tracking-[0.1em] text-text-muted">
          Resolved
        </div>
      </div>
      <div className="flex-1 rounded-md bg-[rgba(255,255,255,0.02)] px-1 py-1.5 text-center">
        <div
          className="font-mono text-sm font-semibold leading-none"
          style={{ color: '#60a5fa' }}
          aria-label={`${active} active sessions`}
        >
          {active}
        </div>
        <div className="mt-1 font-mono text-[7px] uppercase tracking-[0.1em] text-text-muted">
          Active
        </div>
      </div>
      <div className="flex-1 rounded-md bg-[rgba(255,255,255,0.02)] px-1 py-1.5 text-center">
        <div
          className="font-mono text-sm font-semibold leading-none text-muted-foreground"
          aria-label={`${formatDuration(totalSeconds)} total session time today`}
        >
          {formatDuration(totalSeconds)}
        </div>
        <div className="mt-1 font-mono text-[7px] uppercase tracking-[0.1em] text-text-muted">
          Total Time
        </div>
      </div>
    </div>
  )
}
