import React, { ReactNode, useEffect } from 'react';

export function ModalShell({
  label,
  maxWidth,
  onClose,
  children,
}: {
  label: string;
  maxWidth: number;
  onClose: () => void;
  children: ReactNode;
}): JSX.Element {
  useEffect(() => {
    const onKey = (event: KeyboardEvent): void => {
      if (event.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);

    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div
      data-rcm-anim
      onClick={event => {
        if (event.target === event.currentTarget) onClose();
      }}
      style={{ animation: 'rcm-overlay .2s ease both' }}
      className="fixed inset-0 z-50 flex items-start justify-center px-5 py-[clamp(20px,7vh,72px)] overflow-y-auto bg-[rgba(32,34,35,0.45)] backdrop-blur-[4px]"
    >
      <div
        role="dialog"
        aria-modal="true"
        aria-label={label}
        data-rcm-anim
        style={{
          maxWidth: `${maxWidth}px`,
          animation: 'rcm-dialog .26s cubic-bezier(.2,.8,.25,1) both',
        }}
        className="relative w-full p-[26px] bg-white border border-[#e1e3e5] rounded-[18px] shadow-[0_40px_100px_-30px_rgba(0,0,0,0.3)]"
      >
        <button
          type="button"
          onClick={onClose}
          aria-label="Close"
          className="absolute top-4 right-4 inline-flex items-center justify-center w-8 h-8 rounded-[9px] bg-transparent border border-[#e1e3e5] text-[#6d7175] cursor-pointer transition-colors hover:border-[#c9cccf] hover:text-[#202223] hover:bg-[#f6f6f7]"
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <path d="M18 6 6 18" />
            <path d="m6 6 12 12" />
          </svg>
        </button>
        {children}
      </div>
    </div>
  );
}
