'use client'

import React from 'react'
import { RenderElementProps } from 'slate-react'
import { MentionElement } from './mention-plugin'
import useFlowStore from '@/stores/flow-store'
import { useEditorStore } from '@/stores/editor-store'
import { ServerIcon, Zap, Database, MessageSquare, Search, ArrowRightLeft, Layers, UserIcon } from 'lucide-react'
import { getNameFromNode } from './name'

const MentionElementComponent: React.FC<RenderElementProps> = ({ 
  attributes, 
  children, 
  element 
}) => {
  const mention = element as MentionElement
  const { nodes } = useFlowStore()
  const { setSelectedNode } = useEditorStore()

  // Find the referenced node
  const referencedNode = nodes.find(node => node.id === mention.nodeId)
  const label = getNameFromNode(referencedNode)
  const type = mention.nodeType

  // Get icon and styling for node type
  const getNodeStyling = (type: string) => {
    switch (type) {
      case 'actor': return { 
        Icon: UserIcon, 
        className: 'bg-yellow-100 text-yellow-800 border-yellow-300'
      }
      case 'service': return { 
        Icon: ServerIcon, 
        className: 'bg-pink-100 text-pink-800 border-pink-300'
      }
      case 'event': return { 
        Icon: Zap, 
        className: 'bg-orange-100 text-orange-800 border-orange-300'
      }
      case 'data': return { 
        Icon: Database, 
        className: 'bg-blue-100 text-blue-800 border-blue-300'
      }
      case 'command': return { 
        Icon: MessageSquare, 
        className: 'bg-purple-100 text-purple-800 border-purple-300'
      }
      case 'query': return { 
        Icon: Search, 
        className: 'bg-green-100 text-green-800 border-green-300'
      }
      case 'domain': return { 
        Icon: Layers, 
        className: 'bg-indigo-100 text-indigo-800 border-indigo-300'
      }
      case 'channel': return { 
        Icon: ArrowRightLeft, 
        className: 'bg-yellow-100 text-yellow-800 border-yellow-300'
      }
      default: return { 
        Icon: ServerIcon, 
        className: 'bg-gray-100 text-gray-800 border-gray-300'
      }
    }
  }

  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault()
    if (referencedNode) {
      // Jump to the node in the design
      setSelectedNode(mention.nodeId)
    }
  }

  const { Icon, className } = getNodeStyling(type)

  return (
    <span
      {...attributes}
      contentEditable={false}
      className={`inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium border cursor-pointer hover:opacity-80 transition-opacity ${className}`}
      onClick={handleClick}
      title={`${type}: ${label} (click to jump to node)`}
    >
      <Icon className="w-3 h-3" />
      <span>{label}</span>
      <span suppressContentEditableWarning={true} style={{ opacity: 0, position: 'absolute', pointerEvents: 'none' }}>
        {children}
      </span>
    </span>
  )
}

export default MentionElementComponent