import * as React from 'react';
import { ReactNode } from 'react';
import { createPortal } from 'react-dom';
import {
  useHoverPreview,
  getPreviewContainerClassName,
} from '../utils/hoverPreviewUtils';

export interface HoverPreviewProps {
  children: ReactNode;
  previewContent: ReactNode;
  previewClassName?: string;
  maxWidth?: string;
  maxHeight?: string;
}

export const HoverPreview: React.FC<HoverPreviewProps> = ({
  children,
  previewContent,
  previewClassName = '',
  maxWidth = '300px',
  maxHeight = '500px',
}) => {
  // Use shared hover preview hook
  const {
    containerRef,
    previewRef,
    portalContainer,
    showPreview,
    previewStyle,
    handleMouseEnter,
    handleMouseLeave,
  } = useHoverPreview();

  return (
    <span
      ref={containerRef}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      {children}

      {showPreview &&
        createPortal(
          <div
            ref={previewRef}
            className={`${getPreviewContainerClassName(maxWidth, maxHeight)} ${previewClassName}`}
            style={{
              ...previewStyle,
            }}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
          >
            {previewContent}
          </div>,
          portalContainer,
        )}
    </span>
  );
};

export default HoverPreview;
