import { useAgents, useWorkers } from '../hooks/usePulseAPI'
import { useState, useEffect, useMemo, useCallback } from 'react'
import AgentCard from './AgentCard'
import type { AgentData } from './AgentCard'

/* ── Detail modal ── */
function AgentDetailModal({
  agent,
  onClose,
}: {
  agent: AgentData
  onClose: () => void
}) {
  const isActive = agent.status === 'running'

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

  useEffect(() => {
    document.body.style.overflow = 'hidden'
    return () => { document.body.style.overflow = '' }
  }, [])

  const formatUptime = (seconds?: number): string => {
    if (!seconds) 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 ${s}s`
    if (m > 0) return `${m}m ${s}s`
    return `${s}s`
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      aria-label={`Agent details: ${agent.id}`}
    >
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
      <div
        className="relative w-full max-w-lg bg-slate-900/95 backdrop-blur-md border border-slate-700/50 rounded-xl shadow-2xl shadow-black/40"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-slate-700/30">
          <div className="flex items-center gap-3">
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
              isActive ? 'bg-emerald-500/10' : agent.status === 'idle' ? 'bg-amber-400/10' : 'bg-red-500/10'
            }`}>
              <span className="text-sm font-bold text-slate-200">
                {agent.id.slice(0, 2).toUpperCase()}
              </span>
            </div>
            <div>
              <h3 className="text-base font-semibold text-slate-200">{agent.id}</h3>
              <p className="text-xs text-slate-500">{agent.model}</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg bg-slate-800/50 hover:bg-slate-700/50 flex items-center justify-center text-slate-400 hover:text-slate-200 transition-colors"
            aria-label="Close"
          >
            &times;
          </button>
        </div>

        {/* Body */}
        <div className="p-5 space-y-4">
          <div className="grid grid-cols-3 gap-3">
            <DetailField label="Status">
              <span className="flex items-center gap-1.5">
                <span className={`w-2 h-2 rounded-full ${
                  isActive ? 'bg-emerald-500 animate-pulse' : agent.status === 'idle' ? 'bg-amber-400' : 'bg-red-500'
                }`} />
                <span className={`text-sm font-medium capitalize ${
                  isActive ? 'text-emerald-400' : agent.status === 'idle' ? 'text-amber-400' : 'text-red-400'
                }`}>
                  {agent.status === 'dead' ? 'Offline' : agent.status}
                </span>
              </span>
            </DetailField>
            <DetailField label="Tier">
              <span className={`text-sm font-medium uppercase ${
                agent.tier === 'premium' ? 'text-amber-400' :
                agent.tier === 'standard' ? 'text-purple-400' : 'text-blue-400'
              }`}>
                {agent.tier}
              </span>
            </DetailField>
            <DetailField label="Mode">
              <span className={`text-sm font-medium ${
                agent.mode === 'interactive' ? 'text-cyan-400' : 'text-violet-400'
              }`}>
                {agent.mode === 'interactive' ? 'Interactive' : 'Swarm'}
              </span>
            </DetailField>
          </div>

          <DetailField label="Current Task">
            {agent.current_task ? (
              <p className="text-sm text-slate-300">{agent.current_task}</p>
            ) : (
              <p className="text-sm text-slate-600 italic">No active task</p>
            )}
          </DetailField>

          <div className="grid grid-cols-2 gap-3">
            <DetailField label="Uptime">
              <span className="text-sm text-slate-300">{formatUptime(agent.uptime)}</span>
            </DetailField>
            <DetailField label="Last Heartbeat">
              <span className="text-sm text-slate-300">
                {agent.last_heartbeat
                  ? new Date(agent.last_heartbeat).toLocaleTimeString()
                  : '\u2014'}
              </span>
            </DetailField>
          </div>

          {agent.capabilities && agent.capabilities.length > 0 && (
            <DetailField label="Capabilities">
              <div className="flex flex-wrap gap-1.5 mt-1">
                {agent.capabilities.map((cap) => (
                  <span
                    key={cap}
                    className="text-[10px] px-2 py-0.5 rounded-full bg-sky-500/10 text-sky-400 border border-sky-500/20"
                  >
                    {cap}
                  </span>
                ))}
              </div>
            </DetailField>
          )}
        </div>

        <div className="px-5 py-3 border-t border-slate-700/30 flex items-center justify-between">
          <p className="text-[10px] text-slate-600">Press Esc to close</p>
          <button
            onClick={onClose}
            className="text-xs px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition-colors"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  )
}

function DetailField({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <p className="text-[10px] font-medium text-slate-500 uppercase tracking-wider mb-1">
        {label}
      </p>
      {children}
    </div>
  )
}

type FilterType = 'all' | 'swarm' | 'running' | 'idle'

const STATUS_ORDER: Record<string, number> = { running: 0, idle: 1, dead: 2 }

/* ── Unified workforce grid ── */
export default function AgentGrid() {
  const { data: agentsData, loading: agentsLoading } = useAgents()
  const { data: workersData, loading: workersLoading } = useWorkers()
  const [selectedAgent, setSelectedAgent] = useState<AgentData | null>(null)
  const [filter, setFilter] = useState<FilterType>('all')

  const loading = agentsLoading && workersLoading

  /* Merge agents + workers into unified workforce */
  const workforce: AgentData[] = useMemo(() => {
    const agents = (agentsData?.agents || []).map((a: any) => ({
      ...a,
      mode: 'interactive' as const,
      tasks_completed: a.history?.tasks_completed ?? a.tasks_completed ?? 0,
    }))
    const workers = (workersData?.workers || []).map((w: any) => ({
      id: w.id,
      model: w.model,
      tier: w.tier || 'fast',
      type: 'worker' as const,
      mode: 'swarm' as const,
      status: w.status || 'dead',
      current_task: w.current_task,
      last_heartbeat: w.last_heartbeat || w.started_at,
      tasks_completed: w.history?.tasks_completed ?? w.tasks_completed ?? 0,
      capabilities: [],
    }))
    return [...agents, ...workers]
  }, [agentsData, workersData])

  /* Summary counts */
  const running = workforce.filter((a) => a.status === 'running').length
  const idle = workforce.filter((a) => a.status === 'idle').length
  const swarm = workforce.filter((a) => a.mode === 'swarm').length

  /* Filtered + sorted */
  const displayAgents = useMemo(() => {
    let filtered = workforce
    if (filter === 'swarm') filtered = workforce.filter((a) => a.mode === 'swarm')
    else if (filter === 'running' || filter === 'idle')
      filtered = workforce.filter((a) => a.status === filter)
    return [...filtered].sort((a, b) =>
      (STATUS_ORDER[a.status] ?? 9) - (STATUS_ORDER[b.status] ?? 9)
    )
  }, [workforce, filter])

  const closeModal = useCallback(() => setSelectedAgent(null), [])

  if (loading) {
    return (
      <div>
        <h2 className="text-lg font-semibold text-slate-300 mb-4">Workforce</h2>
        <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">Loading workforce...</p>
          </div>
        </div>
      </div>
    )
  }

  if (workforce.length === 0) {
    return (
      <div>
        <h2 className="text-lg font-semibold text-slate-300 mb-4">Workforce</h2>
        <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 agents or workers registered</p>
          <p className="text-slate-600 text-xs mt-2">
            Start agents with <code className="text-sky-400/70 bg-slate-800 px-1.5 py-0.5 rounded">pulse swarm</code> or <code className="text-sky-400/70 bg-slate-800 px-1.5 py-0.5 rounded">pulse claude</code>
          </p>
        </div>
      </div>
    )
  }

  return (
    <div>
      {/* Header + counts + filter tabs */}
      <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">Workforce</h2>
          <div className="flex items-center gap-2 text-xs">
            {running > 0 && (
              <span className="flex items-center gap-1 text-emerald-400">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
                {running}
              </span>
            )}
            {idle > 0 && (
              <span className="flex items-center gap-1 text-amber-400">
                <span className="w-1.5 h-1.5 rounded-full bg-amber-400" />
                {idle}
              </span>
            )}
          </div>
        </div>

        <div className="flex items-center gap-3">
          <div className="flex gap-1 bg-slate-800/60 rounded-lg p-1">
            {([
              { key: 'all', label: 'All' },
              { key: 'swarm', label: `Swarm Crew (${swarm})` },
              { key: 'running', label: 'Running' },
              { key: 'idle', label: 'Idle' },
            ] as const).map((f) => (
              <button
                key={f.key}
                onClick={() => setFilter(f.key)}
                className={`text-xs px-3 py-1 rounded-md transition-colors ${
                  filter === f.key
                    ? 'bg-sky-600/40 text-sky-300'
                    : 'text-slate-500 hover:text-slate-300'
                }`}
              >
                {f.label}
              </button>
            ))}
          </div>
          <p className="text-xs text-slate-600">{workforce.length} total</p>
        </div>
      </div>

      {/* Unified card grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
        {displayAgents.map((agent) => (
          <AgentCard
            key={agent.id}
            agent={agent}
            onClick={() => setSelectedAgent(agent)}
          />
        ))}
      </div>

      {displayAgents.length === 0 && (
        <p className="text-xs text-slate-600 text-center mt-4">
          No {filter} agents &mdash; try &ldquo;All&rdquo;
        </p>
      )}

      {selectedAgent && (
        <AgentDetailModal
          agent={selectedAgent}
          onClose={closeModal}
        />
      )}
    </div>
  )
}
