import React, { useState, useRef } from 'react';
import { createPortal } from 'react-dom';
import styles from './IconButton.module.scss';

export type IconButtonSize = 'large' | 'medium' | 'small';
export type IconButtonVariant = 'tertiary' | 'outlined';

export interface IconButtonProps {
  /** The icon to display inside the button */
  children: React.ReactNode;
  /** Visual variant */
  variant?: IconButtonVariant;
  /** Size variant */
  size?: IconButtonSize;
  /** Click handler */
  onClick?: () => void;
  /** Whether the button is disabled */
  disabled?: boolean;
  /** Accessible label for the button */
  'aria-label': string;
  /** Tooltip shown on hover */
  title?: string;
  /** Additional CSS classes */
  className?: string;
}

const sizeToIconSize: Record<IconButtonSize, number> = {
  large: 20,
  medium: 22,
  small: 14,
};

export const IconButton = ({
  children,
  variant = 'tertiary',
  size = 'medium',
  onClick,
  disabled = false,
  'aria-label': ariaLabel,
  title,
  className = '',
}: IconButtonProps) => {
  const btnRef = useRef<HTMLButtonElement>(null);
  const [tooltipPos, setTooltipPos] = useState<{ top: number; left: number } | null>(null);

  const containerClassName = [
    styles.container,
    styles[size],
    styles[variant],
    disabled && styles.disabled,
    className,
  ]
    .filter(Boolean)
    .join(' ');

  const handleClick = () => {
    if (!disabled && onClick) {
      onClick();
    }
  };

  const handleMouseEnter = () => {
    if (title && btnRef.current) {
      const rect = btnRef.current.getBoundingClientRect();
      setTooltipPos({
        top: rect.bottom + 6,
        left: rect.left + rect.width / 2,
      });
    }
  };

  const handleMouseLeave = () => setTooltipPos(null);

  return (
    <>
      <button
        ref={btnRef}
        className={containerClassName}
        onClick={handleClick}
        disabled={disabled}
        aria-label={ariaLabel}
        type="button"
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      >
        <span className={styles.iconWrapper} style={{ width: sizeToIconSize[size], height: sizeToIconSize[size] }}>
          {children}
        </span>
      </button>
      {title && tooltipPos && createPortal(
        <span
          className={styles.tooltip}
          style={{ top: tooltipPos.top, left: tooltipPos.left }}
        >
          {title}
        </span>,
        document.body
      )}
    </>
  );
};
