import React from 'react'

type TooltipPlacement = 'top' | 'bottom' | 'left' | 'right'

const placementStyles: Record<
  TooltipPlacement,
  { wrapper: string; arrow: string }
> = {
  top: {
    wrapper: 'bottom-full left-1/2 -translate-x-1/2 mb-2',
    arrow: 'top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-slate-800',
  },
  bottom: {
    wrapper: 'top-full left-1/2 -translate-x-1/2 mt-2',
    arrow: 'bottom-full left-1/2 -translate-x-1/2 border-4 border-transparent border-b-slate-800',
  },
  left: {
    wrapper: 'right-full top-1/2 -translate-y-1/2 mr-2',
    arrow: 'left-full top-1/2 -translate-y-1/2 border-4 border-transparent border-l-slate-800',
  },
  right: {
    wrapper: 'left-full top-1/2 -translate-y-1/2 ml-2',
    arrow: 'right-full top-1/2 -translate-y-1/2 border-4 border-transparent border-r-slate-800',
  },
}

export interface TooltipProps {
  content: string
  placement?: TooltipPlacement
  maxWidth?: boolean
  children: React.ReactNode
  className?: string
}

export const Tooltip: React.FC<TooltipProps> = ({
  content,
  placement = 'top',
  maxWidth = false,
  children,
  className = '',
}) => {
  const { wrapper, arrow } = placementStyles[placement]

  return (
    <div className={`relative group inline-flex ${className}`}>
      {children}
      <div
        className={`
          absolute ${wrapper} z-50
          px-3 py-1.5 bg-slate-800 text-white text-caption font-medium rounded-lg
          shadow-soft-lg ${maxWidth ? 'max-w-xs text-center leading-relaxed' : 'whitespace-nowrap'}
          opacity-0 invisible group-hover:opacity-100 group-hover:visible
          transition-all duration-150 pointer-events-none
        `}
      >
        {content}
        <div className={`absolute ${arrow}`} />
      </div>
    </div>
  )
}
