import { Video, Wifi, WifiOff, Signal, Battery, Radio, Play, Square } from 'lucide-react'
import type { CameraStatus } from '../types'

// ── Helpers ────────────────────────────────────────────────────────────────

function formatRelativeTime(iso: string): string {
  const then = new Date(iso).getTime()
  if (isNaN(then)) return 'unknown'

  const diffSec = Math.floor((Date.now() - then) / 1000)
  if (diffSec < 0) return 'unknown'

  if (diffSec < 10) return 'just now'
  if (diffSec < 60) return `${diffSec}s ago`

  const diffMin = Math.floor(diffSec / 60)
  if (diffMin < 60) return `${diffMin}m ago`

  const diffHr = Math.floor(diffMin / 60)
  if (diffHr < 24) return `${diffHr}h ago`

  const diffDay = Math.floor(diffHr / 24)
  return `${diffDay}d ago`
}

function batteryColor(pct: number | null): { status: 'good' | 'low' | 'critical'; bar: string; text: string } {
  if (pct === null) return { status: 'critical', bar: 'bg-rig-dark-600', text: 'text-rig-dark-400' }
  if (pct >= 50) return { status: 'good', bar: 'bg-rig-success', text: 'text-rig-success' }
  if (pct >= 15) return { status: 'low', bar: 'bg-rig-warning', text: 'text-rig-warning' }
  return { status: 'critical', bar: 'bg-rig-danger', text: 'text-rig-danger' }
}

function formatTimeLeft(sec: number): string {
  if (sec <= 0 || !isFinite(sec)) return '--'
  const m = Math.floor(sec / 60)
  const s = Math.floor(sec % 60)
  return `${m}m ${s}s left`
}

function cameraStatus(online: boolean, batteryPct: number | null): 'good' | 'warning' | 'critical' {
  if (!online) return 'critical'
  if (batteryPct === null) return 'good'
  if (batteryPct >= 50) return 'good'
  if (batteryPct >= 15) return 'warning'
  return 'critical'
}

const STATUS_BORDER: Record<string, string> = {
  good: 'border-l-rig-success',
  warning: 'border-l-rig-warning',
  critical: 'border-l-rig-danger',
}

// ── Component ──────────────────────────────────────────────────────────────

interface CameraCardProps {
  camera: CameraStatus
  onStart: (cameraId: string) => void
  onStop: (cameraId: string) => void
  onViewHistory: (cameraId: string) => void
  disabled?: boolean
}

export default function CameraCard({ camera, onStart, onStop, onViewHistory, disabled }: CameraCardProps) {
  const {
    camera_id,
    friendly_name,
    online,
    resolution,
    fps,
    recording,
    mode,
    battery_pct,
    last_seen,
    video_remaining_sec,
  } = camera

  const batt = batteryColor(battery_pct)
  const status = cameraStatus(online, battery_pct)
  const borderColor = STATUS_BORDER[status]

  return (
    <article
      className={`rounded-xl border border-rig-dark-600 bg-rig-dark-800/60 transition-colors border-l-4 ${borderColor} ${
        online
          ? 'hover:border-rig-accent/40'
          : 'opacity-75'
      }`}
    >
      {/* ── Header ── */}
      <div className="flex items-center justify-between px-4 pt-4 pb-2">
        <div className="flex items-center gap-2 min-w-0">
          <Video className="h-4 w-4 shrink-0 text-rig-accent" aria-hidden="true" />
          <h3
            className="text-sm font-semibold text-rig-dark-100 truncate"
            title={friendly_name}
          >
            {friendly_name}
          </h3>
        </div>

        {/* Online / Offline badge */}
        <span
          role="status"
          aria-label={online ? 'Camera online' : 'Camera offline'}
          className={`ml-2 shrink-0 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium ${
            online
              ? 'bg-rig-success/15 text-rig-success'
              : 'bg-rig-danger/15 text-rig-danger'
          }`}
        >
          {online ? (
            <Wifi className="h-3 w-3" aria-hidden="true" />
          ) : (
            <WifiOff className="h-3 w-3" aria-hidden="true" />
          )}
          {online ? 'Online' : 'Offline'}
        </span>
      </div>

      {/* ── Body ── */}
      <div className="space-y-2.5 px-4 pb-3">
        {/* Camera ID */}
        <p className="text-[11px] font-mono text-rig-dark-500">{camera_id}</p>

        {/* Resolution + FPS */}
        <div className="flex items-center gap-1.5 text-xs text-rig-dark-300">
          <Signal className="h-3.5 w-3.5" />
          <span>
            {resolution} &middot; {fps} FPS
          </span>
        </div>

        {/* Recording state */}
        <div className="flex items-center gap-2">
          {recording ? (
            <>
              <span
                className="relative flex h-2.5 w-2.5"
                role="status"
                aria-label="Recording in progress"
              >
                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-rig-danger opacity-75" />
                <span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-rig-danger" />
              </span>
              <span className="rounded bg-rig-danger/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-rig-danger">
                REC
              </span>
            </>
          ) : (
            <span className="rounded bg-rig-dark-600/50 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-rig-dark-400">
              IDLE
            </span>
          )}
          <span className="text-[11px] text-rig-dark-400">{mode}</span>
        </div>

        {/* Battery */}
        <div className="space-y-1">
          <div className="flex items-center justify-between text-xs">
            <span className="flex items-center gap-1 text-rig-dark-400">
              <Battery className="h-3 w-3" />
              Battery
            </span>
            <span className={`font-mono text-xs ${batt.text}`}>
              {battery_pct !== null ? `${Math.max(0, battery_pct)}%` : 'N/A'}
            </span>
          </div>
          <div
            className="h-1.5 w-full overflow-hidden rounded-full bg-rig-dark-700"
            role="progressbar"
            aria-valuenow={battery_pct ?? 0}
            aria-valuemin={0}
            aria-valuemax={100}
            aria-label={`Battery ${battery_pct !== null ? battery_pct + '%' : 'unknown'}`}
          >
            <div
              className={`h-full rounded-full transition-all ${batt.bar}`}
              style={{ width: battery_pct !== null ? `${Math.min(100, Math.max(0, battery_pct))}%` : '0%' }}
            />
          </div>
        </div>
      </div>

      {/* ── Footer ── */}
      <div className="rounded-b-xl border-t border-rig-dark-700/50 bg-rig-dark-900/30">
        {/* Controls row */}
        <div className="flex items-center gap-1 px-3 py-2">
          {recording ? (
            <button
              onClick={() => onStop(camera_id)}
              disabled={disabled}
              className="flex items-center gap-1 rounded-md bg-rig-danger/20 px-2.5 py-1 text-xs font-medium text-rig-danger hover:bg-rig-danger/30 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              aria-label={`Stop recording ${friendly_name}`}
            >
              <Square className="h-3 w-3 fill-current" />
              Stop
            </button>
          ) : (
            <button
              onClick={() => onStart(camera_id)}
              disabled={disabled || !online}
              className="flex items-center gap-1 rounded-md bg-rig-success/20 px-2.5 py-1 text-xs font-medium text-rig-success hover:bg-rig-success/30 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              aria-label={`Start recording ${friendly_name}`}
            >
              <Play className="h-3 w-3 fill-current" />
              Record
            </button>
          )}
          <button
            onClick={() => onViewHistory(camera_id)}
            className="ml-auto rounded-md bg-rig-dark-700/50 px-2 py-1 text-[11px] text-rig-dark-300 hover:bg-rig-dark-600 hover:text-rig-dark-100 transition-colors"
          >
            History
          </button>
        </div>

        {/* Status strip */}
        <div className="flex items-center justify-between px-4 pb-2">
          <div className="flex items-center gap-1.5 text-xs">
            {online ? (
              <>
                <span className="h-1.5 w-1.5 rounded-full bg-rig-success" />
                <span className="text-rig-success">Live</span>
              </>
            ) : (
              <span className="text-rig-dark-400">Offline</span>
            )}
            <span className="text-rig-dark-500">·</span>
            <span className="text-rig-dark-400">{formatRelativeTime(last_seen)}</span>
          </div>

          {video_remaining_sec !== null && (
            <div className="flex items-center gap-1 text-xs text-rig-dark-400">
              <Radio className="h-3 w-3" />
              <span className="font-mono">{formatTimeLeft(video_remaining_sec)}</span>
            </div>
          )}
        </div>
      </div>
    </article>
  )
}
