import { useEffect, useState } from 'react'
import { X, Clock, Battery, Radio, Video } from 'lucide-react'
import { api } from '../services/api'
import type { StatusLog } from '../types'

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

function formatTimestamp(iso: string): string {
  const d = new Date(iso)
  if (isNaN(d.getTime())) return iso
  return d.toLocaleString(undefined, {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

function batteryColor(pct: number | null): string {
  if (pct === null) return 'text-rig-dark-400'
  if (pct >= 50) return 'text-rig-success'
  if (pct >= 15) return 'text-rig-warning'
  return 'text-rig-danger'
}

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

interface HistoryViewerProps {
  cameraId: string | null
  cameraName?: string
  onClose: () => void
}

export default function HistoryViewer({ cameraId, cameraName, onClose }: HistoryViewerProps) {
  const [logs, setLogs] = useState<StatusLog[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!cameraId) {
      setLogs([])
      return
    }

    setLoading(true)
    setError(null)

    api
      .getCameraDetail(cameraId)
      .then((data) => {
        setLogs(data.history)
      })
      .catch((err) => {
        setError(err instanceof Error ? err.message : 'Failed to load history')
      })
      .finally(() => setLoading(false))
  }, [cameraId])

  // Handle escape key
  useEffect(() => {
    function onKeyDown(e: KeyboardEvent) {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', onKeyDown)
    return () => document.removeEventListener('keydown', onKeyDown)
  }, [onClose])

  if (cameraId === null) return null

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose()
      }}
      role="dialog"
      aria-modal="true"
      aria-label={`History for ${cameraName ?? cameraId}`}
    >
      <div className="mx-4 w-full max-w-2xl max-h-[85vh] flex flex-col rounded-xl border border-rig-dark-600 bg-rig-dark-800 shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between rounded-t-xl border-b border-rig-dark-700 px-5 py-4">
          <div className="flex items-center gap-2">
            <Clock className="h-4 w-4 text-rig-accent" />
            <h2 className="text-sm font-semibold text-rig-dark-100">
              History &mdash; {cameraName ?? cameraId}
            </h2>
          </div>
          <button
            onClick={onClose}
            className="rounded-md p-1 text-rig-dark-400 hover:bg-rig-dark-700 hover:text-rig-dark-100 transition-colors"
            aria-label="Close history"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-5 py-4">
          {loading && (
            <div className="flex items-center justify-center py-12">
              <div className="h-5 w-5 animate-spin rounded-full border-2 border-rig-dark-500 border-t-rig-accent" />
              <span className="ml-3 text-sm text-rig-dark-400">Loading history...</span>
            </div>
          )}

          {error && (
            <div className="rounded-lg border border-rig-danger/30 bg-rig-danger/10 px-4 py-3 text-sm text-rig-danger">
              {error}
            </div>
          )}

          {!loading && !error && logs.length === 0 && (
            <p className="py-8 text-center text-sm text-rig-dark-400">
              No history entries found for this camera.
            </p>
          )}

          {!loading && logs.length > 0 && (
            <div className="space-y-2">
              {logs.map((log) => (
                <div
                  key={log.id}
                  className="flex items-center gap-3 rounded-lg border border-rig-dark-700/50 bg-rig-dark-900/40 px-3 py-2.5 text-xs"
                >
                  {/* Timestamp */}
                  <span className="font-mono text-rig-dark-400 min-w-[130px]">
                    {formatTimestamp(log.recorded_at)}
                  </span>

                  {/* Online/Recording badges */}
                  <div className="flex items-center gap-2">
                    <span
                      className={`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium ${
                        log.online
                          ? 'bg-rig-success/15 text-rig-success'
                          : 'bg-rig-danger/15 text-rig-danger'
                      }`}
                    >
                      {log.online ? 'Online' : 'Offline'}
                    </span>

                    {log.recording_state ? (
                      <span className="rounded bg-rig-danger/15 px-1.5 py-0.5 text-[10px] font-bold uppercase text-rig-danger">
                        REC
                      </span>
                    ) : (
                      <span className="rounded bg-rig-dark-600/50 px-1.5 py-0.5 text-[10px] text-rig-dark-500">
                        IDLE
                      </span>
                    )}
                  </div>

                  {/* Battery */}
                  <div className="flex items-center gap-1 ml-auto">
                    <Battery className="h-3 w-3 text-rig-dark-500" />
                    <span className={`font-mono ${batteryColor(log.battery_pct)}`}>
                      {log.battery_pct !== null ? `${log.battery_pct}%` : 'N/A'}
                    </span>
                  </div>

                  {/* Storage remaining */}
                  {log.video_remaining_sec !== null && (
                    <div className="flex items-center gap-1">
                      <Radio className="h-3 w-3 text-rig-dark-500" />
                      <span className="font-mono text-rig-dark-400">
                        {Math.floor(log.video_remaining_sec / 60)}m left
                      </span>
                    </div>
                  )}

                  {/* Mode */}
                  <div className="flex items-center gap-1">
                    <Video className="h-3 w-3 text-rig-dark-500" />
                    <span className="text-rig-dark-400">{log.mode}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="rounded-b-xl border-t border-rig-dark-700 px-5 py-3">
          <p className="text-[11px] text-rig-dark-500">
            {logs.length} entries (last 24 hours)
          </p>
        </div>
      </div>
    </div>
  )
}
