import { useEffect, useId, useState } from 'react';
import { Icon } from '../../Atoms/Icon/Icon';
import {
  MODAL_SHELL_OVERLAY_BG,
  MODAL_SHELL_TITLE_STYLE,
} from './modalShellStyles';

/**
 * Shell de modal con overlay y panel al estilo VistaDatos.
 *
 * @param {boolean} [isOpen]
 * @param {function} [onClose]
 * @param {string} [title]
 * @param {string} [closeAriaLabel]
 * @param {boolean} [closeOnOverlayClick]
 * @param {boolean} [showCloseButton]
 * @param {number} [mobileBreakpoint]
 * @param {number} [zIndex]
 * @param {number|string} [width] — Ancho desktop del panel (px o CSS).
 * @param {number|string} [height] — Alto desktop del panel.
 * @param {number|string} [maxHeight]
 * @param {React.ReactNode} [footer]
 * @param {object} [footerStyle]
 * @param {object} [headerStyle]
 * @param {object} [bodyStyle]
 * @param {object} [panelStyle]
 * @param {object} [overlayStyle]
 */
export const ModalShell = ({
  isOpen = false,
  onClose,
  title,
  titleId: titleIdProp,
  closeAriaLabel = 'Cerrar modal',
  closeOnOverlayClick = true,
  showCloseButton = true,
  mobileBreakpoint = 768,
  zIndex = 1500,
  width = 580,
  height,
  maxHeight,
  footer,
  footerStyle,
  headerStyle,
  bodyStyle,
  panelStyle,
  overlayStyle,
  className = '',
  panelClassName = '',
  children,
  ...props
}) => {
  const autoTitleId = useId();
  const titleId = titleIdProp ?? autoTitleId;
  const [viewportWidth, setViewportWidth] = useState(
    typeof window !== 'undefined' ? window.innerWidth : 1920,
  );

  useEffect(() => {
    if (!isOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [isOpen]);

  useEffect(() => {
    if (typeof window === 'undefined') return undefined;
    const handleResize = () => setViewportWidth(window.innerWidth);
    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  if (!isOpen) return null;

  const isMobile = viewportWidth <= mobileBreakpoint;
  const hasTitle = Boolean(title && String(title).trim());
  const desktopWidth = typeof width === 'number' ? `${width}px` : width;
  const desktopHeight = height != null ? (typeof height === 'number' ? `${height}px` : height) : undefined;
  const desktopMaxHeight =
    maxHeight != null
      ? typeof maxHeight === 'number'
        ? `${maxHeight}px`
        : maxHeight
      : 'calc(100vh - 40px)';

  const handleOverlayClick = () => {
    if (closeOnOverlayClick) onClose?.();
  };

  return (
    <div
      className={`anima-modal-shell__overlay ${className}`.trim()}
      style={{
        position: 'fixed',
        inset: 0,
        zIndex,
        background: MODAL_SHELL_OVERLAY_BG,
        display: 'flex',
        alignItems: isMobile ? 'stretch' : 'center',
        justifyContent: 'center',
        padding: isMobile ? 0 : 20,
        boxSizing: 'border-box',
        ...overlayStyle,
      }}
      onClick={handleOverlayClick}
      {...props}
    >
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby={hasTitle ? titleId : undefined}
        className={`anima-modal-shell__panel ${panelClassName}`.trim()}
        onClick={(event) => event.stopPropagation()}
        style={{
          width: isMobile ? '100%' : desktopWidth,
          maxWidth: '100%',
          height: isMobile ? '100%' : desktopHeight,
          maxHeight: isMobile ? '100%' : desktopMaxHeight,
          borderRadius: isMobile ? 0 : 16,
          background: '#FFFFFF',
          border: '1px solid #C4C4C4',
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
          ...panelStyle,
        }}
      >
        {(hasTitle || showCloseButton) && (
          <div
            className="anima-modal-shell__header"
            style={{
              flexShrink: 0,
              padding: isMobile ? '12px 10px 10px' : '16px 16px 12px',
              borderBottom: '1px solid #E5E7EB',
              display: 'flex',
              alignItems: 'flex-start',
              justifyContent: 'space-between',
              gap: 12,
              boxSizing: 'border-box',
              ...headerStyle,
            }}
          >
            {hasTitle ? (
              <h2 id={titleId} className="anima-modal-shell__title" style={MODAL_SHELL_TITLE_STYLE}>
                {title}
              </h2>
            ) : (
              <div style={{ flex: 1 }} />
            )}
            {showCloseButton ? (
              <button
                type="button"
                aria-label={closeAriaLabel}
                onClick={() => onClose?.()}
                style={{
                  border: 'none',
                  background: 'transparent',
                  padding: 0,
                  marginTop: 2,
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexShrink: 0,
                }}
              >
                <Icon name="XMarkIcon" variant="24-outline" size={22} style={{ color: '#29474C' }} />
              </button>
            ) : null}
          </div>
        )}

        <div
          className="anima-modal-shell__body"
          style={{
            flex: 1,
            minHeight: 0,
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
            boxSizing: 'border-box',
            ...bodyStyle,
          }}
        >
          {children}
        </div>

        {footer != null ? (
          <div
            className="anima-modal-shell__footer"
            style={{
              flexShrink: 0,
              padding: isMobile ? '10px 12px' : '12px 16px',
              borderTop: '1px solid #E5E7EB',
              background: '#FFFFFF',
              display: 'flex',
              flexDirection: 'row',
              flexWrap: 'nowrap',
              justifyContent: 'flex-end',
              alignItems: 'center',
              gap: 8,
              boxSizing: 'border-box',
              ...(footerStyle || {}),
            }}
          >
            {footer}
          </div>
        ) : null}
      </div>
    </div>
  );
};

export default ModalShell;
