import { useCallback, useEffect, useId, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useClickOutside } from '../../hooks/useClickOutside';
import { useModalA11y } from '../../hooks/useModalA11y';
import { CloseIcon } from './icons';
import { IconButton } from './IconButton';

interface InfoPopupProps {
  title: string;
  children: ReactNode;
  onClose: () => void;
  sourceLink?: { label: string; onClick: () => void };
}

export default function InfoPopup({ title, children, onClose, sourceLink }: InfoPopupProps) {
  const popupRef = useModalA11y();
  const titleId = useId();

  const handleClose = useCallback(() => {
    onClose();
  }, [onClose]);

  useClickOutside(popupRef, handleClose);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [onClose]);

  const popup = (
    <div
      className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/50 p-4 dark:bg-black/70"
      role="presentation"
    >
      <div
        ref={popupRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        tabIndex={-1}
        className="bg-white dark:bg-warm-800 border border-warm-200 dark:border-warm-700 rounded-lg shadow-xl max-w-md w-full max-h-full overflow-y-auto p-5 outline-none"
      >
        <div className="flex items-start justify-between mb-3">
          <h3 id={titleId} className="text-sm font-semibold text-warm-900 dark:text-warm-100 pr-4">
            {title}
          </h3>
          <IconButton onClick={onClose} className="shrink-0">
            <CloseIcon />
          </IconButton>
        </div>
        {children}
        {sourceLink && (
          <button
            onClick={sourceLink.onClick}
            className="text-sm text-teal-600 dark:text-teal-400 hover:text-teal-800 dark:hover:text-teal-300 hover:underline"
          >
            {sourceLink.label}
          </button>
        )}
      </div>
    </div>
  );

  if (typeof document === 'undefined') return popup;

  return createPortal(popup, document.body);
}
