import { motion } from 'framer-motion'
import type { Connection, Agent } from '../types/agent'
import { cn } from '../lib/utils'

interface ConnectionsLayerProps {
  connections: Connection[]
  agents: Agent[]
  highlightedAgentId: string | null
}

const connectionTypeStyles = {
  delegates: { color: '#22c55e', dashArray: '8 4' },
  reports: { color: '#3b82f6', dashArray: '0 0' },
  requests: { color: '#eab308', dashArray: '4 4' },
  transfers: { color: '#8b5cf6', dashArray: '12 4' }
}

export function ConnectionsLayer({ connections, agents, highlightedAgentId }: ConnectionsLayerProps) {
  const getAgentPosition = (agentId: string) => {
    const agent = agents.find(a => a.id === agentId)
    if (!agent) return { x: 0, y: 0 }
    return {
      x: (agent.position.x / 100) * 800, // Canvas width
      y: (agent.position.y / 100) * 600   // Canvas height
    }
  }

  const isConnectionHighlighted = (connection: Connection) => {
    if (!highlightedAgentId) return false
    return connection.from === highlightedAgentId || connection.to === highlightedAgentId
  }

  return (
    <svg className="absolute inset-0 w-full h-full pointer-events-none">
      <defs>
        {/* Glow filter */}
        <filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="3" result="coloredBlur" />
          <feMerge>
            <feMergeNode in="coloredBlur" />
            <feMergeNode in="SourceGraphic" />
          </feMerge>
        </filter>
        
        {/* Arrow marker */}
        <marker
          id="arrowhead"
          markerWidth="10"
          markerHeight="7"
          refX="9"
          refY="3.5"
          orient="auto"
        >
          <polygon points="0 0, 10 3.5, 0 7" fill="currentColor" />
        </marker>
      </defs>

      {connections.map((connection) => {
        const from = getAgentPosition(connection.from)
        const to = getAgentPosition(connection.to)
        const styles = connectionTypeStyles[connection.type]
        const isHighlighted = isConnectionHighlighted(connection)
        const isActive = connection.active

        // Calculate control point for curved line
        const midX = (from.x + to.x) / 2
        const midY = (from.y + to.y) / 2
        const dx = to.x - from.x
        const dy = to.y - from.y
        const ctrlX = midX - dy * 0.2
        const ctrlY = midY + dx * 0.2

        return (
          <g key={connection.id}>
            {/* Shadow/glow line */}
            {isHighlighted && (
              <motion.path
                d={`M ${from.x} ${from.y} Q ${ctrlX} ${ctrlY} ${to.x} ${to.y}`}
                stroke={styles.color}
                strokeWidth={6}
                fill="none"
                opacity={0.2}
                filter="url(#glow)"
                initial={{ pathLength: 0 }}
                animate={{ pathLength: 1 }}
                transition={{ duration: 0.5 }}
              />
            )}
            
            {/* Main line */}
            <motion.path
              d={`M ${from.x} ${from.y} Q ${ctrlX} ${ctrlY} ${to.x} ${to.y}`}
              stroke={styles.color}
              strokeWidth={isHighlighted ? 3 : 2}
              strokeOpacity={isHighlighted ? 1 : 0.4}
              fill="none"
              strokeDasharray={styles.dashArray}
              className={cn(
                'transition-all duration-300',
                isActive && 'connection-line'
              )}
              style={{ 
                filter: isHighlighted ? 'url(#glow)' : undefined,
                color: styles.color
              }}
              markerEnd="url(#arrowhead)"
              initial={{ pathLength: 0 }}
              animate={{ pathLength: 1 }}
              transition={{ duration: 0.8, delay: connection.id.charCodeAt(1) * 0.05 }}
            />
          </g>
        )
      })}
    </svg>
  )
}
