import * as React from 'react'

import { cn } from './utils'

/* ------------------------------------------------------------------ */
/*  Types                                                              */
/* ------------------------------------------------------------------ */

export type UptimeSegmentStatus = 'up' | 'down' | 'degraded' | 'unknown'

export interface UptimeSegment {
  status: UptimeSegmentStatus
  tooltip?: string
}

/* ------------------------------------------------------------------ */
/*  Helpers                                                            */
/* ------------------------------------------------------------------ */

function calculateUptimePercent(segments: UptimeSegment[]): string {
  if (segments.length === 0) return '0.0'
  let upCount = 0
  for (const segment of segments) {
    if (segment.status === 'up') upCount += 1
  }
  return ((upCount / segments.length) * 100).toFixed(1)
}

const statusColors: Record<UptimeSegmentStatus, string> = {
  up: 'bg-accent-emerald',
  down: 'bg-accent-rose',
  degraded: 'bg-accent-amber',
  unknown: 'bg-foreground-muted/40',
}

/* ------------------------------------------------------------------ */
/*  UptimeBar                                                          */
/* ------------------------------------------------------------------ */

export interface UptimeBarProps extends React.ComponentProps<'div'> {
  segments: UptimeSegment[]
  /** Show the uptime percentage label. Defaults to true. */
  showLabel?: boolean
  /** Height of the segment bar in pixels. Defaults to 32. */
  height?: number
}

function UptimeBar({
  className,
  segments,
  showLabel = true,
  height = 32,
  ...props
}: UptimeBarProps) {
  const percent = calculateUptimePercent(segments)

  return (
    <div
      data-slot="uptime-bar"
      role="img"
      aria-label={`Uptime status bar: ${percent}% uptime`}
      className={cn('flex flex-col gap-2', className)}
      {...props}
    >
      {/* Segments */}
      <div className="flex w-full gap-[2px] overflow-hidden rounded-md" style={{ height }}>
        {segments.map((segment, i) => (
          <div
            key={i}
            title={segment.tooltip}
            className={cn(
              'flex-1 transition-colors duration-200',
              'first:rounded-l-md last:rounded-r-md',
              'hover:opacity-80',
              statusColors[segment.status]
            )}
          />
        ))}
        {segments.length === 0 && <div className="flex-1 rounded-md bg-surface-secondary" />}
      </div>

      {/* Label */}
      {showLabel && (
        <div className="flex items-center justify-between text-xs text-foreground-secondary">
          <span>{percent}% uptime</span>
          <span className="text-foreground-muted">{segments.length} checks</span>
        </div>
      )}
    </div>
  )
}

export { UptimeBar }
