import { useCallback, useEffect, useId, useRef } from 'react';
import GlassSurface from './GlassSurface';
import useFocusTrap from '../../lib/use-focus-trap';

const SIZE_MAX_WIDTH = {
  sm: '24rem',
  md: '32rem',
  lg: '48rem',
  'fullscreen-on-mobile': '32rem',
};

export default function Modal({
  open,
  onClose,
  title,
  description,
  size = 'md',
  closeOnBackdrop = true,
  closeOnEsc = true,
  initialFocusRef,
  hideCloseButton = false,
  children,
}) {
  const panelRef = useRef(null);
  const titleId = useId();
  const descriptionId = useId();

  useFocusTrap({ active: open, containerRef: panelRef, initialFocusRef });

  useEffect(() => {
    if (!open || !closeOnEsc) return undefined;
    const handler = (e) => {
      if (e.key === 'Escape') onClose?.();
    };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [open, closeOnEsc, onClose]);

  useEffect(() => {
    if (!open) return undefined;
    const previousOverflow = document.body.style.overflow;
    const previousPadRight = document.body.style.paddingRight;
    const scrollbarWidth =
      window.innerWidth - document.documentElement.clientWidth;
    document.body.style.overflow = 'hidden';
    if (scrollbarWidth > 0) {
      document.body.style.paddingRight = `${scrollbarWidth}px`;
    }
    return () => {
      document.body.style.overflow = previousOverflow;
      document.body.style.paddingRight = previousPadRight;
    };
  }, [open]);

  const handleBackdropClick = useCallback(
    (e) => {
      if (!closeOnBackdrop) return;
      if (e.target === e.currentTarget) onClose?.();
    },
    [closeOnBackdrop, onClose]
  );

  if (!open) return null;

  const isFullscreenOnMobile = size === 'fullscreen-on-mobile';
  const maxWidth = SIZE_MAX_WIDTH[size] ?? SIZE_MAX_WIDTH.md;

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby={titleId}
      aria-describedby={description ? descriptionId : undefined}
      onClick={handleBackdropClick}
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{
        background: 'var(--modal-scrim)',
        backdropFilter:
          'blur(var(--glass-blur-high)) saturate(var(--glass-saturate))',
        WebkitBackdropFilter:
          'blur(var(--glass-blur-high)) saturate(var(--glass-saturate))',
      }}
    >
      <GlassSurface
        ref={panelRef}
        tint="low"
        blur="mid"
        rim="subtle"
        elevation="pronounced"
        className={`relative w-full overflow-y-auto rounded-2xl ${
          isFullscreenOnMobile
            ? 'max-h-screen sm:max-h-[90vh]'
            : 'max-h-[90vh]'
        }`}
        style={{
          maxWidth: isFullscreenOnMobile ? '100%' : maxWidth,
          color: 'var(--text-primary)',
        }}
      >
        <div className="flex items-start justify-between gap-4 px-6 pt-6 pb-3">
          <div className="flex-1 min-w-0">
            <h2
              id={titleId}
              className="text-xl font-bold"
              style={{ color: 'var(--text-primary)' }}
            >
              {title}
            </h2>
            {description && (
              <p
                id={descriptionId}
                className="mt-1 text-sm"
                style={{ color: 'var(--text-secondary)' }}
              >
                {description}
              </p>
            )}
          </div>
          {!hideCloseButton && (
            <button
              type="button"
              onClick={onClose}
              aria-label="Close"
              className="-mt-1 -mr-1 inline-flex h-9 w-9 items-center justify-center rounded-full transition-opacity hover:opacity-70 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2"
              style={{
                color: 'var(--text-secondary)',
                '--tw-ring-color': 'var(--accent-ember)',
                '--tw-ring-offset-color': 'transparent',
              }}
            >
              <svg
                className="h-5 w-5"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                aria-hidden="true"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          )}
        </div>
        <div className="px-6 pb-6">{children}</div>
      </GlassSurface>
    </div>
  );
}
