import { useEffect, useState } from 'react'
import { Button } from './Button'

export interface WrapperRateLimit {
  wrapper: string
  active: boolean
  account?: string
  resumeAtMs?: number
  wait?: number
  max?: number
  parkedTasks?: string[]
  affectedSeats?: string[]
}

function formatCountdown(resumeAtMs: number, nowMs: number) {
  const seconds = Math.max(0, Math.ceil((resumeAtMs - nowMs) / 1_000))
  return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
}

export function WrapperCapacity(props: {
  wrappers: string[]
  ratelimits: WrapperRateLimit[]
  dataAvailable: boolean
  onOpen(wrapper: string): void
}) {
  const [nowMs, setNowMs] = useState(() => Date.now())

  useEffect(() => {
    if (!props.dataAvailable || !props.ratelimits.some((limit) => limit.active && limit.resumeAtMs)) {
      return
    }
    const timer = setInterval(() => setNowMs(Date.now()), 1_000)
    return () => clearInterval(timer)
  }, [props.dataAvailable, props.ratelimits])

  return (
    <div className="flex flex-wrap items-center gap-1.5" aria-label="Wrapper capacity">
      {props.wrappers.length === 0 && (
        <span data-tipb="Capacity unavailable" data-tips="no limit data yet (B7)" className="text-xs text-fg-muted">
          account: not recorded · wrappers not recorded yet (B7)
        </span>
      )}
      {props.wrappers.map((wrapper) => {
        const limit = props.ratelimits.find((candidate) => candidate.wrapper === wrapper)
        const label = !props.dataAvailable
          ? wrapper
          : limit?.active
            ? `${wrapper} ⏳${limit.resumeAtMs ? formatCountdown(limit.resumeAtMs, nowMs) : 'limited'}`
            : `${wrapper} ✓`

        return (
          <Button
            key={wrapper}
            type="button"
            variant="outline"
            tone="neutral"
            size="sm"
            data-tipb={props.dataAvailable ? `${wrapper} capacity` : `${wrapper} capacity unavailable`}
            data-tips={props.dataAvailable ? undefined : 'no limit data yet (B7)'}
            onClick={() => props.onOpen(wrapper)}
            className="tabular-nums text-xs"
          >
            {label}
          </Button>
        )
      })}
    </div>
  )
}