import { useWorkers } from '../hooks/usePulseAPI'
import { useState, useMemo } from 'react'

/* ── tier badge colors ── */
const TIER_COLORS: Record<string, string> = {
  fast: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
  standard: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
  premium: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
}

/* ── status config ── */
const STATUS_CONFIG: Record<string, { dot: string; label: string; ring: string }> = {
  running: { dot: 'bg-emerald-500', label: 'Running', ring: 'ring-emerald-500/30' },
  idle: { dot: 'bg-sky-400', label: 'Idle', ring: 'ring-sky-400/30' },
  stopped: { dot: 'bg-slate-500', label: 'Stopped', ring: 'ring-slate-500/30' },
  error: { dot: 'bg-red-500', label: 'Error', ring: 'ring-red-500/30' },
}

function formatUptime(seconds?: number): string {
  if (!seconds || seconds <= 0) return '\u2014'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  if (h > 0) return `${h}h ${m}m`
  if (m > 0) return `${m}m ${s}s`
  return `${s}s`
}

function formatHeartbeat(ts?: string): string {
  if (!ts) return '\u2014'
  try {
    const d = new Date(ts)
    const now = Date.now()
    const diffSec = Math.floor((now - d.getTime()) / 1000)
    if (diffSec < 10) return 'just now'
    if (diffSec < 60) return `${diffSec}s ago`
    if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m ago`
    return d.toLocaleTimeString()
  } catch {
    return '\u2014'
  }
}

function WorkerCard({ worker }: { worker: any }) {
  const status = STATUS_CONFIG[worker.status] || STATUS_CONFIG.stopped
  const tierColor = TIER_COLORS[worker.tier] || TIER_COLORS.fast
  const isActive = worker.status === 'running'

  const iterations = worker.iterations || 0
  const maxIterations = worker.max_iterations || 15
  const progress = maxIterations > 0 ? Math.min((iterations / maxIterations) * 100, 100) : 0

  return (
    <div
      className={`bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-4
        transition-all duration-300 hover:border-sky-500/30
        ${isActive ? `ring-1 ${status.ring}` : ''}`}
    >
      {/* Header: model + status */}
      <div className="flex items-start justify-between mb-3">
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold text-slate-200 truncate">
            {worker.model || 'Unknown'}
          </p>
          <p className="text-xs text-slate-500 mt-0.5 font-mono">PID {worker.pid}</p>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <span
            className={`w-2.5 h-2.5 rounded-full ${status.dot} ${
              isActive ? 'animate-pulse' : ''
            }`}
          />
          <span className={`text-xs px-2 py-0.5 rounded border ${tierColor} font-medium uppercase`}>
            {worker.tier}
          </span>
        </div>
      </div>

      {/* Status + Uptime row */}
      <div className="flex items-center justify-between mb-3 pb-3 border-b border-slate-700/30">
        <div>
          <p className="text-xs text-slate-400 uppercase tracking-wider">Status</p>
          <p className={`text-sm font-medium mt-0.5 ${
            isActive ? 'text-emerald-400' : 'text-slate-400'
          }`}>
            {status.label}
          </p>
        </div>
        <div className="text-right">
          <p className="text-xs text-slate-400 uppercase tracking-wider">Uptime</p>
          <p className="text-sm text-slate-300 font-medium mt-0.5">
            {formatUptime(worker.uptime)}
          </p>
        </div>
      </div>

      {/* Task progress bar (visible when running) */}
      {isActive && worker.current_task && (
        <div className="mb-3">
          <div className="flex items-center justify-between mb-1">
            <p className="text-xs text-slate-400 uppercase tracking-wider">Progress</p>
            <p className="text-xs text-slate-500">{iterations}/{maxIterations}</p>
          </div>
          <div className="w-full bg-slate-700/50 rounded-full h-1.5">
            <div
              className="h-1.5 rounded-full bg-sky-500 transition-all duration-500"
              style={{ width: `${progress}%` }}
            />
          </div>
        </div>
      )}

      {/* Current task */}
      {worker.current_task ? (
        <div className="mb-3">
          <p className="text-xs text-slate-400 uppercase tracking-wider mb-1">Current Task</p>
          <p className="text-xs text-slate-300 line-clamp-2">{worker.current_task}</p>
        </div>
      ) : (
        <p className="text-xs text-slate-600 italic mb-3">Waiting for tasks...</p>
      )}

      {/* Footer: tasks completed + last heartbeat */}
      <div className="flex items-center justify-between pt-3 border-t border-slate-700/30">
        <div>
          <p className="text-[10px] text-slate-500 uppercase">Completed</p>
          <p className="text-xs text-emerald-400 font-bold">
            {worker.tasks_completed ?? 0}
          </p>
        </div>
        <div className="text-right">
          <p className="text-[10px] text-slate-500 uppercase">Heartbeat</p>
          <p className={`text-xs font-medium ${
            worker.last_heartbeat ? 'text-slate-400' : 'text-slate-600'
          }`}>
            {formatHeartbeat(worker.last_heartbeat)}
          </p>
        </div>
      </div>
    </div>
  )
}

/* ── Aggregate stats strip ── */
function AggregateStats({ workers }: { workers: any[] }) {
  const stats = useMemo(() => {
    const running = workers.filter((w: any) => w.status === 'running').length
    const idle = workers.filter((w: any) => w.status === 'idle').length
    const totalCompleted = workers.reduce((sum: number, w: any) => sum + (w.tasks_completed || 0), 0)
    const avgUptime = workers.length > 0
      ? workers.reduce((sum: number, w: any) => sum + (w.uptime || 0), 0) / workers.length
      : 0
    const models = new Set(workers.map((w: any) => w.model).filter(Boolean))
    return { running, idle, totalCompleted, avgUptime, modelCount: models.size }
  }, [workers])

  return (
    <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-4">
      {[
        { label: 'Active', value: stats.running, color: 'text-emerald-400' },
        { label: 'Idle', value: stats.idle, color: 'text-sky-400' },
        { label: 'Total Done', value: stats.totalCompleted, color: 'text-amber-400' },
        { label: 'Avg Uptime', value: formatUptime(stats.avgUptime), color: 'text-slate-300' },
        { label: 'Models', value: stats.modelCount, color: 'text-violet-400' },
      ].map((s) => (
        <div key={s.label} className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg px-3 py-2">
          <p className="text-[10px] text-slate-500 uppercase tracking-wider">{s.label}</p>
          <p className={`text-lg font-bold ${s.color}`}>{s.value}</p>
        </div>
      ))}
    </div>
  )
}

export default function WorkerMonitor() {
  const { data: workersData, loading } = useWorkers()
  const [filter, setFilter] = useState<'all' | 'running' | 'idle'>('all')

  const workers: any[] = workersData?.workers || []
  const filtered =
    filter === 'all'
      ? workers
      : workers.filter((w: any) => w.status === filter)

  const runningCount = workers.filter((w: any) => w.status === 'running').length
  const idleCount = workers.filter((w: any) => w.status === 'idle').length

  return (
    <div>
      {/* Header + filter + counts */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <h2 className="text-lg font-semibold text-slate-300">Workers</h2>
          <div className="flex items-center gap-2 text-xs text-slate-500">
            <span className="flex items-center gap-1">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
              {runningCount}
            </span>
            <span className="flex items-center gap-1">
              <span className="w-1.5 h-1.5 rounded-full bg-sky-400" />
              {idleCount}
            </span>
            <span className="text-slate-600">/ {workers.length}</span>
          </div>
        </div>
        <div className="flex gap-1 bg-slate-800/60 rounded-lg p-1">
          {(['all', 'running', 'idle'] as const).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`text-xs px-3 py-1 rounded-md capitalize transition-colors ${
                filter === f
                  ? 'bg-sky-600/40 text-sky-300'
                  : 'text-slate-500 hover:text-slate-300'
              }`}
            >
              {f}
            </button>
          ))}
        </div>
      </div>

      {/* Loading state */}
      {loading && (
        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-8 flex items-center justify-center">
          <div className="flex items-center gap-3">
            <span className="w-2 h-2 rounded-full bg-sky-400 animate-pulse" />
            <p className="text-sm text-slate-500">Connecting to workers...</p>
          </div>
        </div>
      )}

      {/* Empty state */}
      {!loading && workers.length === 0 && (
        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-8 text-center">
          <p className="text-slate-500 text-sm">No workers online</p>
          <p className="text-slate-600 text-xs mt-2">
            Start workers with: <code className="text-sky-400/70 bg-slate-800 px-1.5 py-0.5 rounded">pulse swarm</code>
          </p>
        </div>
      )}

      {/* Aggregate stats (only when workers exist) */}
      {!loading && workers.length > 0 && (
        <AggregateStats workers={workers} />
      )}

      {/* Worker grid */}
      {!loading && filtered.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
          {filtered.map((w: any) => (
            <WorkerCard key={w.pid} worker={w} />
          ))}
        </div>
      )}

      {/* Filtered-out notice */}
      {!loading && workers.length > 0 && filtered.length === 0 && (
        <p className="text-xs text-slate-600 text-center mt-4">
          No {filter} workers &mdash; try &ldquo;all&rdquo;
        </p>
      )}
    </div>
  )
}
