import { useState, ReactNode, useCallback } from 'react'

interface TooltipProps {
  children: ReactNode
  title?: ReactNode | string
  className?: string
  placement?: 'top' | 'bottom'
}

export const Tooltip = ({ children, title, className = '', placement = 'top' }: TooltipProps) => {
  const [isVisible, setIsVisible] = useState(false)

  const handleMouseEnter = useCallback(() => setIsVisible(true), [])
  const handleMouseLeave = useCallback(() => setIsVisible(false), [])

  if (!title) {
    return children
  }

  const isTop = placement === 'top'

  const positionClasses = isTop ? 'bottom-full mb-2' : 'top-full mt-2'

  const arrowClasses = isTop ? 'top-full -mt-1 border-t-gray-800' : 'bottom-full -mb-1 border-b-gray-800'

  return (
    <div
      className={`relative inline-block ${className}`}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      {children}
      {isVisible && (
        <div
          className={`absolute left-1/2 z-[9999] -translate-x-1/2 whitespace-nowrap rounded-md bg-blue-100 px-3 py-2 text-sm text-secondary shadow-lg pointer-events-none ${positionClasses}`}
        >
          {title}

          <div className={`absolute left-1/2 -translate-x-1/2 border-4 border-transparent ${arrowClasses}`} />
        </div>
      )}
    </div>
  )
}
