/**
 * Article: card/panel con header (título + cerrar), bloque de contenido (icono advertencia opcional + texto) y footer con botones primario y secundario.
 * Reutiliza Typography, Icon, PrimaryActionButton, FONT_FAMILY_SANS y tokens de color. Especificación Figma: header 24/24/6/24, título 20/30 #29474C, contenido gap 20, icono #F8DBDB borde #B30808, footer border-top grey-90.
 */
import { Typography } from '../../Atoms/Typography/Typography';
import { Icon } from '../../Atoms/Icon/Icon';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { FONT_FAMILY_SANS } from '../../../designTokens';

const COLOR_MAIN_800 = 'var(--color-main-800, #29474C)';
const COLOR_ERROR_BORDER = '#B30808';
const COLOR_WARNING_BG = '#F8DBDB';
const BORDER_TOP_FOOTER = '1px solid var(--color-grey-90, #E5E5E5)';

export const Article = ({
  title = '',
  onClose,
  /** Si se pasa, se muestra el bloque con icono de advertencia (fondo #F8DBDB, borde #B30808) y este texto. */
  message,
  /** Contenido alternativo al message: nodos React. Si no hay message ni children, no se renderiza cuerpo. */
  children,
  primaryButtonText = '',
  onPrimaryClick,
  secondaryButtonText = '',
  onSecondaryClick,
  className = '',
  style = {},
  headerStyle = {},
  contentStyle = {},
  footerStyle = {},
  withOverlay = false,
  overlayStyle = {},
  overlayClassName = '',
  overlayCloseOnClick = false,
  onOverlayClick,
  ...props
}) => {
  const hasContent = (message != null && message !== '') || children != null;

  const articleNode = (
    <article
      className={`anima-article ${className}`}
      style={{
        width: '100%',
        maxWidth: 566,
        borderRadius: 16,
        overflow: 'hidden',
        opacity: 1,
        backgroundColor: '#FFFFFF',
        border: '1px solid var(--color-grey-90, #E5E5E5)',
        boxShadow: '0 20px 50px rgba(0, 0, 0, 0.2)',
        ...style,
      }}
      onClick={(event) => {
        // Evita que un click dentro del artículo cierre el modal por bubbling.
        event.stopPropagation();
      }}
      {...props}
    >
      {/* Header: título + icono cerrar */}
      <div
        className="anima-article__header"
        style={{
          paddingTop: 24,
          paddingRight: 24,
          paddingBottom: 20,
          paddingLeft: 24,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 12,
          minHeight: 60,
          boxSizing: 'border-box',
          ...headerStyle,
        }}
      >
        <Typography
          variant="h6"
          weight="regular"
          component="div"
          style={{
            fontFamily: FONT_FAMILY_SANS,
            fontWeight: 400,
            fontSize: '20px',
            lineHeight: '30px',
            letterSpacing: '0%',
            color: COLOR_MAIN_800,
            margin: 0,
            flex: 1,
            minWidth: 0,
          }}
        >
          {title}
        </Typography>
        {onClose && (
          <button
            type="button"
            onClick={onClose}
            aria-label="Cerrar"
            style={{
              border: 'none',
              background: 'none',
              padding: 0,
              cursor: 'pointer',
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              flexShrink: 0,
            }}
          >
            <Icon name="XMarkIcon" variant="24-outline" size={24} />
          </button>
        )}
      </div>

      {/* Contenido: opcional icono advertencia + texto */}
      {hasContent && (
        <div
          className="anima-article__content"
          style={{
            paddingTop: 12,
            paddingRight: 24,
            paddingLeft: 24,
            paddingBottom: 24,
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'flex-start',
            gap: 20,
            borderRadius: 16,
            boxSizing: 'border-box',
            ...contentStyle,
          }}
        >
          {message != null && message !== '' && (
            <div
              style={{
                width: 40,
                height: 40,
                padding: 8,
                borderRadius: 12,
                background: COLOR_WARNING_BG,
                boxSizing: 'border-box',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                flexShrink: 0,
              }}
            >
              <Icon
                name="ExclamationTriangleIcon"
                variant="24-outline"
                size={24}
                style={{ color: COLOR_ERROR_BORDER }}
              />
            </div>
          )}
          <div
            style={{
              flex: 1,
              minWidth: 0,
            }}
          >
            {message != null && message !== '' && !children ? (
              <Typography
                variant="body-lg"
                style={{
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 400,
                  fontSize: '16px',
                  lineHeight: '24px',
                  letterSpacing: 0,
                  color: COLOR_MAIN_800,
                  margin: 0,
                }}
              >
                {message}
              </Typography>
            ) : (
              children
            )}
          </div>
        </div>
      )}

      {/* Footer: borde superior + botones */}
      <div
        className="anima-article__footer"
        style={{
          display: 'flex',
          flexDirection: 'row',
          flexWrap: 'nowrap',
          alignItems: 'center',
          justifyContent: 'flex-end',
          gap: 20,
          padding: 20,
          borderTop: BORDER_TOP_FOOTER,
          boxSizing: 'border-box',
          minHeight: 80,
          ...footerStyle,
        }}
      >
        <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 20, flexShrink: 0 }}>
          {secondaryButtonText && (
            <PrimaryActionButton
              variant="outline"
              text={secondaryButtonText}
              onClick={onSecondaryClick}
              type="button"
            />
          )}
          {primaryButtonText && (
            <PrimaryActionButton
              variant="primary"
              text={primaryButtonText}
              onClick={onPrimaryClick}
              type="button"
            />
          )}
        </div>
      </div>
    </article>
  );

  if (!withOverlay) return articleNode;

  return (
    <div
      className={`anima-article__overlay ${overlayClassName}`.trim()}
      style={{
        position: 'fixed',
        inset: 0,
        background: 'rgba(0, 0, 0, 0.35)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 10001,
        padding: '16px',
        boxSizing: 'border-box',
        ...overlayStyle,
      }}
      onClick={(event) => {
        if (event.target !== event.currentTarget) return;
        if (!overlayCloseOnClick) return;
        onOverlayClick?.(event);
        onClose?.();
      }}
    >
      {articleNode}
    </div>
  );
};

export default Article;
