import React, { useState } from 'react';
import { HelpCircle } from 'lucide-react';

export interface TooltipProps {
  content: string;
  children: React.ReactNode;
  position?: 'top' | 'right' | 'bottom' | 'left';
  className?: string;
}

const positionStyles = {
  top: 'bottom-full left-1/2 -translate-x-1/2 mb-2',
  right: 'left-full top-1/2 -translate-y-1/2 ml-2',
  bottom: 'top-full left-1/2 -translate-x-1/2 mt-2',
  left: 'right-full top-1/2 -translate-y-1/2 mr-2',
};

const arrowStyles = {
  top: 'top-full left-1/2 -translate-x-1/2 border-l-transparent border-r-transparent border-b-transparent border-t-[#1d1d1d]',
  right: 'right-full top-1/2 -translate-y-1/2 border-t-transparent border-b-transparent border-l-transparent border-r-[#1d1d1d]',
  bottom: 'bottom-full left-1/2 -translate-x-1/2 border-l-transparent border-r-transparent border-t-transparent border-b-[#1d1d1d]',
  left: 'left-full top-1/2 -translate-y-1/2 border-t-transparent border-b-transparent border-r-transparent border-l-[#1d1d1d]',
};

export const Tooltip: React.FC<TooltipProps> = ({
  content,
  children,
  position = 'top',
  className = '',
}) => {
  const [isVisible, setIsVisible] = useState(false);

  return (
    <div
      className={`relative inline-block ${className}`}
      onMouseEnter={() => setIsVisible(true)}
      onMouseLeave={() => setIsVisible(false)}
      onFocus={() => setIsVisible(true)}
      onBlur={() => setIsVisible(false)}
    >
      {children}
      {isVisible && (
        <div
          className={`${positionStyles[position]} absolute z-50 w-64 rounded-lg border border-[#2a2a2a] bg-[#1d1d1d] p-3 shadow-lg`}
          role="tooltip"
        >
          <p className="text-xs font-mono leading-5 text-[#e0e0e0]">{content}</p>
          <div
            className={`absolute ${arrowStyles[position]} border-4`}
            aria-hidden="true"
          />
        </div>
      )}
    </div>
  );
};

export const HelpIcon: React.FC<{ tooltip: string; className?: string }> = ({
  tooltip,
  className = '',
}) => {
  return (
    <Tooltip content={tooltip} className={className}>
      <button
        type="button"
        className="ml-1 rounded text-[#666666] transition-colors hover:text-[#58a6ff] focus:outline-none focus:ring-2 focus:ring-[#58a6ff] focus:ring-offset-2 focus:ring-offset-[#111111]"
        aria-label="Get help"
      >
        <HelpCircle className="h-4 w-4" />
      </button>
    </Tooltip>
  );
};
