import { useEffect, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import styles from './SideDrawer.module.css';

interface SideDrawerProps {
  open: boolean;
  onClose: () => void;
  title: ReactNode;
  size?: 'md' | 'lg' | 'xl';
  footer?: ReactNode;
  children: ReactNode;
}

export function SideDrawer({
  open, onClose, title, size = 'lg', footer, children,
}: SideDrawerProps): React.JSX.Element | null {
  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [open, onClose]);

  if (!open) return null;

  return createPortal(
    <div className={styles.root}>
      <div
        className={styles.backdrop}
        data-testid="side-drawer-backdrop"
        onClick={onClose}
      />
      <aside
        className={`${styles.drawer} ${styles[`size-${size}`]}`}
        role="dialog"
        aria-modal="true"
      >
        <header className={styles.header}>
          <div className={styles.title}>{title}</div>
          <button
            type="button"
            aria-label="Close drawer"
            className={styles.closeBtn}
            onClick={onClose}
          >
            ×
          </button>
        </header>
        <div className={styles.body}>{children}</div>
        {footer && <footer className={styles.footer}>{footer}</footer>}
      </aside>
    </div>,
    document.body
  );
}
