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-term-highlight',
  right: 'right-full top-1/2 -translate-y-1/2 border-t-transparent border-b-transparent border-l-transparent border-r-term-highlight',
  bottom: 'bottom-full left-1/2 -translate-x-1/2 border-l-transparent border-r-transparent border-t-transparent border-b-term-highlight',
  left: 'left-full top-1/2 -translate-y-1/2 border-t-transparent border-b-transparent border-r-transparent border-l-term-highlight',
};

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-term-border bg-term-highlight p-3 shadow-lg`}
          role="tooltip"
        >
          <p className="text-xs font-mono leading-5 text-term-text">{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-term-text-tertiary transition-colors hover:text-info focus:outline-none focus:ring-2 focus:ring-info focus:ring-offset-2 focus:ring-offset-term-surface"
        aria-label="Get help"
      >
        <HelpCircle className="h-4 w-4" />
      </button>
    </Tooltip>
  );
};
