import { motion, AnimatePresence } from 'framer-motion'
import { X, Activity, Clock, CheckCircle2, AlertCircle, MessageSquare } from 'lucide-react'
import type { Agent } from '../types/agent'
import { cn } from '../lib/utils'
import { timelineEvents } from '../data/agents'

interface AgentDetailPanelProps {
  agent: Agent | null
  onClose: () => void
}

const statusConfig = {
  active: { label: 'Activo', color: 'text-agent-active', bg: 'bg-agent-active/20', icon: Activity },
  blocked: { label: 'Bloqueado', color: 'text-agent-blocked', bg: 'bg-agent-blocked/20', icon: AlertCircle },
  thinking: { label: 'Pensando', color: 'text-agent-thinking', bg: 'bg-agent-thinking/20', icon: Clock },
  idle: { label: 'Inactivo', color: 'text-agent-idle', bg: 'bg-agent-idle/20', icon: Clock },
  completed: { label: 'Completado', color: 'text-agent-completed', bg: 'bg-agent-completed/20', icon: CheckCircle2 }
}

const roleDescriptions = {
  orchestrator: 'Coordina y delega tareas entre el equipo',
  architect: 'Diseña sistemas y arquitectura de soluciones',
  developer: 'Implementa código y funcionalidades',
  designer: 'Crea interfaces y experiencia de usuario',
  reviewer: 'Valida calidad y revisa implementaciones',
  assistant: 'Gestiona documentación y organización'
}

export function AgentDetailPanel({ agent, onClose }: AgentDetailPanelProps) {
  if (!agent) {
    return (
      <div className="h-full flex items-center justify-center text-gray-500 text-sm">
        Selecciona un agente para ver detalles
      </div>
    )
  }

  const status = statusConfig[agent.status]
  const StatusIcon = status.icon
  const agentEvents = timelineEvents.filter(e => e.agentId === agent.id).slice(0, 5)

  return (
    <AnimatePresence mode="wait">
      <motion.div
        key={agent.id}
        initial={{ opacity: 0, x: 20 }}
        animate={{ opacity: 1, x: 0 }}
        exit={{ opacity: 0, x: -20 }}
        transition={{ duration: 0.2 }}
        className="h-full flex flex-col"
      >
        {/* Header */}
        <div className="flex items-start justify-between p-4 border-b border-glass-border">
          <div className="flex items-center gap-3">
            <div className="w-14 h-14 rounded-2xl bg-background-lighter flex items-center justify-center text-3xl border border-glass-border">
              {agent.avatar}
            </div>
            <div>
              <h2 className="text-xl font-semibold">{agent.name}</h2>
              <p className="text-sm text-gray-400">{roleDescriptions[agent.role]}</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg hover:bg-background-lighter transition-colors"
          >
            <X className="w-5 h-5 text-gray-400" />
          </button>
        </div>

        {/* Status */}
        <div className="p-4 border-b border-glass-border">
          <div className={cn('inline-flex items-center gap-2 px-3 py-1.5 rounded-full', status.bg)}>
            <StatusIcon className={cn('w-4 h-4', status.color)} />
            <span className={cn('text-sm font-medium', status.color)}>{status.label}</span>
          </div>
          {agent.currentTask && (
            <p className="mt-3 text-sm text-gray-300">
              <span className="text-gray-500">Tarea actual:</span> {agent.currentTask}
            </p>
          )}
        </div>

        {/* Stats */}
        <div className="p-4 border-b border-glass-border">
          <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">Estadísticas</h3>
          <div className="grid grid-cols-3 gap-3">
            <div className="text-center p-3 rounded-xl bg-agent-completed/10 border border-agent-completed/20">
              <p className="text-2xl font-bold text-agent-completed">{agent.stats.tasksCompleted}</p>
              <p className="text-[10px] text-gray-500 uppercase">Completadas</p>
            </div>
            <div className="text-center p-3 rounded-xl bg-agent-active/10 border border-agent-active/20">
              <p className="text-2xl font-bold text-agent-active">{agent.stats.tasksInProgress}</p>
              <p className="text-[10px] text-gray-500 uppercase">En Progreso</p>
            </div>
            <div className="text-center p-3 rounded-xl bg-agent-blocked/10 border border-agent-blocked/20">
              <p className="text-2xl font-bold text-agent-blocked">{agent.stats.tasksBlocked}</p>
              <p className="text-[10px] text-gray-500 uppercase">Bloqueadas</p>
            </div>
          </div>
        </div>

        {/* Connections */}
        <div className="p-4 border-b border-glass-border">
          <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">Conexiones</h3>
          <div className="flex flex-wrap gap-2">
            {agent.connections.map(connId => (
              <span
                key={connId}
                className="px-2 py-1 text-xs rounded-lg bg-background-lighter border border-glass-border"
              >
                {connId}
              </span>
            ))}
          </div>
        </div>

        {/* Recent Activity */}
        <div className="p-4 flex-1 overflow-y-auto">
          <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">
            Actividad Reciente
          </h3>
          <div className="space-y-3">
            {agentEvents.length > 0 ? agentEvents.map(event => (
              <motion.div
                key={event.id}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex gap-3 text-sm"
              >
                <div className="mt-1">
                  {event.type === 'task_start' && <Activity className="w-3.5 h-3.5 text-agent-active" />}
                  {event.type === 'task_complete' && <CheckCircle2 className="w-3.5 h-3.5 text-agent-completed" />}
                  {event.type === 'task_blocked' && <AlertCircle className="w-3.5 h-3.5 text-agent-blocked" />}
                  {event.type === 'message' && <MessageSquare className="w-3.5 h-3.5 text-agent-thinking" />}
                  {event.type === 'transfer' && <MessageSquare className="w-3.5 h-3.5 text-purple-400" />}
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-gray-300 truncate">{event.description}</p>
                  <p className="text-[10px] text-gray-500">
                    {event.timestamp.toLocaleTimeString()}
                  </p>
                </div>
              </motion.div>
            )) : (
              <p className="text-sm text-gray-500">Sin actividad reciente</p>
            )}
          </div>
        </div>
      </motion.div>
    </AnimatePresence>
  )
}
