import { useEffect, useState } from 'react';
import { Icon } from '../../Atoms/Icon/Icon';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { BadgeAzul } from '../../Atoms/BadgeAzul/BadgeAzul';
import { TablaSearch } from '../Tabla/TablaSearch';
import {
  VistaDatosDetalleAlerta,
  VISTA_DATOS_DETALLE_ALERT_STYLE,
} from './VistaDatosDetalleAlerta';
import { VistaDatosDetallePanel } from './VistaDatosDetallePanel';
import { VistaDatosDocumentosList } from './VistaDatosDocumentosList';
import { FONT_FAMILY_SANS } from '../../../designTokens';

/** Ancho del panel en desktop (spec diseño). */
export const VISTA_DATOS_DESKTOP_WIDTH_PX = 1038;
/** Alto del panel en desktop (spec diseño). */
export const VISTA_DATOS_DESKTOP_HEIGHT_PX = 690;
/** Ancho de cada columna interna (spec diseño). */
export const VISTA_DATOS_COLUMN_WIDTH_PX = 485;
/** Alto de cada columna interna (spec diseño). */
export const VISTA_DATOS_COLUMN_HEIGHT_PX = 479;

/** Estilo base de cada panel (detalles / listado). */
export const VISTA_DATOS_COLUMN_PANEL_STYLE = {
  width: VISTA_DATOS_COLUMN_WIDTH_PX,
  height: VISTA_DATOS_COLUMN_HEIGHT_PX,
  borderRadius: 16,
  border: '1px solid #C4C4C4',
  borderTop: '1px solid #C4C4C4',
  background: '#FFFFFF',
  boxSizing: 'border-box',
  opacity: 1,
  display: 'flex',
  flexDirection: 'column',
  overflow: 'hidden',
};

/** Título de columna (DETALLES / LISTADO DE DOCUMENTOS). */
export const VISTA_DATOS_COLUMN_TITLE_STYLE = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 400,
  fontStyle: 'normal',
  fontSize: '20px',
  lineHeight: '30px',
  letterSpacing: 0,
  verticalAlign: 'middle',
  textTransform: 'uppercase',
  color: '#29474C',
  margin: 0,
};

/** «DATOS DE LA CARGA» — IBM Plex Sans Medium 14/21, 1% tracking, mayúsculas. */
export const VISTA_DATOS_SECTION_LABEL_STYLE = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 500,
  fontStyle: 'normal',
  fontSize: '14px',
  lineHeight: '21px',
  letterSpacing: '0.01em',
  textTransform: 'uppercase',
  color: '#29474C',
  margin: 0,
};

/** Nombre de archivo — IBM Plex Sans SemiBold 20/30. */
export const VISTA_DATOS_FILE_NAME_STYLE = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 600,
  fontStyle: 'normal',
  fontSize: '20px',
  lineHeight: '30px',
  letterSpacing: 0,
  verticalAlign: 'middle',
  color: '#29474C',
  margin: 0,
};

/** Caja del buscador en listado de documentos (spec diseño). */
export const VISTA_DATOS_SEARCH_BOX_STYLE = {
  width: '100%',
  maxWidth: 445,
  height: 40,
  borderRadius: 8,
  borderWidth: 1,
  borderStyle: 'solid',
  borderColor: 'var(--color-grey-600, #5F5F5F)',
  gap: 12,
  opacity: 1,
  paddingTop: 8,
  paddingRight: 12,
  paddingBottom: 8,
  paddingLeft: 12,
  flex: '0 0 auto',
  boxSizing: 'border-box',
};

/**
 * Modal «Vista de datos». Shell + cabecera (etiqueta de sección + nombre de archivo).
 * El resto del contenido va en `children` / `body`.
 *
 * @param {boolean} [isOpen]
 * @param {function} [onClose]
 * @param {string} [sectionLabel] — Ej. «DATOS DE LA CARGA»
 * @param {object} [sectionLabelStyle]
 * @param {string} [fileName] — Ej. «Política interna 2020 a 2026.zip»
 * @param {object} [fileNameStyle]
 * @param {string} [title] — @deprecated Alias de `fileName` si `fileName` no se define
 * @param {object} [headerStyle]
 * @param {string} [closeAriaLabel]
 * @param {boolean} [closeOnOverlayClick]
 * @param {number} [mobileBreakpoint]
 * @param {number} [zIndex]
 * @param {boolean} [showColumnHeaders] — Muestra título en cada columna.
 * @param {string} [leftColumnTitle] — Default: «DETALLES».
 * @param {string} [rightColumnTitle] — Default: «LISTADO DE DOCUMENTOS».
 * @param {object} [leftColumnTitleStyle]
 * @param {object} [rightColumnTitleStyle]
 * @param {React.ReactNode} [rightColumnBadge] — Badge custom (prioridad sobre `rightColumnBadgeLabel`).
 * @param {string} [rightColumnBadgeLabel] — Texto simple del badge (ej. «4 documentos»).
 * @param {object} [columnHeaderStyle]
 * @param {object} [columnContentStyle]
 * @param {React.ReactNode} [leftPanelContent] — Contenido custom (prioridad sobre panel detalle).
 * @param {boolean} [showDetallePanel] — Renderiza `VistaDatosDetallePanel` si no hay `leftPanelContent`.
 * @param {object} [detallePanelProps] — Props de `VistaDatosDetallePanel` (empresa, metadata, stats).
 * @param {boolean} [showLeftColumnAlert] — Muestra banner de advertencia en detalles.
 * @param {string} [leftColumnAlertMessage] — Texto del banner (default incorporación parcial).
 * @param {React.ReactNode} [leftColumnAlert] — Banner custom (prioridad sobre `showLeftColumnAlert`).
 * @param {object} [leftColumnAlertStyle] — Estilos del contenedor del banner.
 * @param {React.ReactNode} [rightPanelContent] — Contenido custom (prioridad sobre listado documentos).
 * @param {boolean} [showDocumentosList] — Listado + paginado + scroll verde en columna documentos.
 * @param {Array<object>} [documentos] — Ítems del listado.
 * @param {number} [documentosPageSize] — Ítems por página (default 4).
 * @param {number} [documentosCurrentPage] — Página controlada (1-based).
 * @param {function} [onDocumentosPageChange]
 * @param {object} [documentosListProps] — Props extra de `VistaDatosDocumentosList`.
 * @param {boolean} [showRightColumnSearch] — Muestra el buscador de Tabla en listado de documentos.
 * @param {string} [rightColumnSearchValue]
 * @param {function} [onRightColumnSearchChange] — `(value, event)`.
 * @param {string} [rightColumnSearchPlaceholder] — Default: «Buscar por nombre o legajo».
 * @param {React.ReactNode} [rightColumnSearch] — Buscador custom (prioridad sobre props de búsqueda).
 * @param {object} [rightColumnSearchBoxStyle] — Estilos de la caja del buscador (default `VISTA_DATOS_SEARCH_BOX_STYLE`).
 * @param {number} [columnWidth]
 * @param {number} [columnHeight]
 * @param {object} [columnPanelStyle] — Estilos de cada panel (se fusionan con el default).
 * @param {object} [leftColumnPanelStyle]
 * @param {object} [rightColumnPanelStyle]
 * @param {number} [columnsGap]
 * @param {object} [columnsContainerStyle]
 * @param {React.ReactNode} [children] — Si se define, sustituye el layout de dos columnas.
 * @param {React.ReactNode} [body] — Alias de `children`.
 * @param {boolean} [showFooter]
 * @param {string} [closeButtonLabel]
 * @param {string} [downloadReportButtonLabel]
 * @param {function} [onDownloadReport]
 * @param {object} [closeButtonProps]
 * @param {object} [downloadReportButtonProps]
 * @param {React.ReactNode} [footer] — Sustituye el footer por defecto (botones).
 * @param {object} [footerStyle]
 */
export const VistaDatos = ({
  isOpen = false,
  onClose,
  sectionLabel = 'DATOS DE LA CARGA',
  sectionLabelStyle,
  fileName: fileNameProp,
  fileNameStyle,
  title,
  headerStyle,
  closeAriaLabel = 'Cerrar modal',
  closeOnOverlayClick = true,
  mobileBreakpoint = 768,
  zIndex = 1500,
  showColumnHeaders = true,
  leftColumnTitle = 'DETALLES',
  rightColumnTitle = 'LISTADO DE DOCUMENTOS',
  leftColumnTitleStyle,
  rightColumnTitleStyle,
  rightColumnBadge,
  rightColumnBadgeLabel,
  columnHeaderStyle,
  columnContentStyle,
  leftPanelContent,
  showDetallePanel = false,
  detallePanelProps,
  showLeftColumnAlert = false,
  leftColumnAlertMessage,
  leftColumnAlert,
  leftColumnAlertStyle,
  rightPanelContent,
  showDocumentosList = false,
  documentos,
  documentosPageSize = 4,
  documentosCurrentPage,
  onDocumentosPageChange,
  documentosListProps,
  showRightColumnSearch = true,
  rightColumnSearchValue,
  onRightColumnSearchChange,
  rightColumnSearchPlaceholder = 'Buscar por nombre o legajo',
  rightColumnSearch,
  rightColumnSearchBoxStyle,
  columnWidth = VISTA_DATOS_COLUMN_WIDTH_PX,
  columnHeight = VISTA_DATOS_COLUMN_HEIGHT_PX,
  columnPanelStyle,
  leftColumnPanelStyle,
  rightColumnPanelStyle,
  columnsGap = 16,
  columnsContainerStyle,
  children,
  body,
  showFooter = true,
  closeButtonLabel = 'Cerrar',
  downloadReportButtonLabel = 'Descargar informe',
  onDownloadReport,
  onDownloadReportClick,
  closeButtonProps,
  downloadReportButtonProps,
  footer,
  footerStyle,
  className = '',
  style,
  overlayStyle,
  panelStyle,
  ...props
}) => {
  const [viewportWidth, setViewportWidth] = useState(
    typeof window !== 'undefined' ? window.innerWidth : 1920,
  );

  const fileName =
    fileNameProp !== undefined && fileNameProp !== null
      ? fileNameProp
      : title !== undefined && title !== null
        ? title
        : 'Política interna 2020 a 2026.zip';

  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 bodyOverride = body ?? children;
  const hasSectionLabel = Boolean(sectionLabel && String(sectionLabel).trim());

  const columnPanelBaseStyle = {
    ...VISTA_DATOS_COLUMN_PANEL_STYLE,
    width: isMobile ? '100%' : columnWidth,
    maxWidth: '100%',
    height: isMobile ? 'auto' : columnHeight,
    minHeight: isMobile ? Math.min(columnHeight, 320) : columnHeight,
    ...(columnPanelStyle || {}),
  };

  const renderDocumentsBadge = () => {
    if (rightColumnBadge != null) return rightColumnBadge;
    if (!rightColumnBadgeLabel || !String(rightColumnBadgeLabel).trim()) return null;
    return <BadgeAzul>{rightColumnBadgeLabel}</BadgeAzul>;
  };

  const renderLeftColumnAlert = () => {
    if (leftColumnAlert != null) return leftColumnAlert;
    if (!showLeftColumnAlert) return null;
    return (
      <VistaDatosDetalleAlerta
        message={leftColumnAlertMessage}
        style={{
          ...VISTA_DATOS_DETALLE_ALERT_STYLE,
          ...(isMobile ? { width: '100%', maxWidth: '100%' } : {}),
          ...(leftColumnAlertStyle || {}),
        }}
      />
    );
  };

  const renderLeftPanelContent = () => {
    if (leftPanelContent != null) return leftPanelContent;
    if (!showDetallePanel) return null;
    return <VistaDatosDetallePanel isNarrow={isMobile} {...(detallePanelProps || {})} />;
  };

  const renderRightPanelContent = () => {
    if (rightPanelContent != null) return rightPanelContent;
    if (!showDocumentosList) return null;
    return (
      <VistaDatosDocumentosList
        documentos={documentos}
        searchQuery={rightColumnSearchValue}
        pageSize={documentosPageSize}
        currentPage={documentosCurrentPage}
        onPageChange={onDocumentosPageChange}
        isNarrow={isMobile}
        {...(documentosListProps || {})}
      />
    );
  };

  const renderRightColumnSearch = () => {
    if (!showRightColumnSearch) return null;
    if (rightColumnSearch != null) return rightColumnSearch;
    return (
      <TablaSearch
        searchValue={rightColumnSearchValue}
        onSearchChange={onRightColumnSearchChange}
        searchPlaceholder={rightColumnSearchPlaceholder}
        boxStyle={{
          ...VISTA_DATOS_SEARCH_BOX_STYLE,
          ...(isMobile ? { width: '100%', maxWidth: '100%' } : {}),
          ...(rightColumnSearchBoxStyle || {}),
        }}
        wrapStyle={{ width: isMobile ? '100%' : 'auto' }}
      />
    );
  };

  const renderColumnPanel = ({
    side,
    columnTitle,
    columnTitleStyle,
    columnBadge,
    columnSearch,
    columnAlert,
    content,
    extraStyle,
  }) => {
    const hasColumnTitle = Boolean(columnTitle && String(columnTitle).trim());

    return (
      <div
        className={`anima-vista-datos__column anima-vista-datos__column--${side}`}
        style={{
          ...columnPanelBaseStyle,
          ...(extraStyle || {}),
        }}
      >
        {showColumnHeaders && hasColumnTitle ? (
          <div
            className="anima-vista-datos__column-header"
            style={{
              flexShrink: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: 8,
              padding: '24px 14px 12px',
              boxSizing: 'border-box',
              minWidth: 0,
              ...(columnHeaderStyle || {}),
            }}
          >
            <h3
              className="anima-vista-datos__column-title"
              style={{
                ...VISTA_DATOS_COLUMN_TITLE_STYLE,
                ...(columnTitleStyle || {}),
              }}
            >
              {columnTitle}
            </h3>
            {columnBadge ? (
              <div className="anima-vista-datos__column-header-badge" style={{ flexShrink: 0 }}>
                {columnBadge}
              </div>
            ) : null}
          </div>
        ) : null}
        {columnSearch ? (
          <div
            className="anima-vista-datos__column-search"
            style={{
              flexShrink: 0,
              padding: isMobile
                ? '0 10px 4px'
                : side === 'right'
                  ? '0 14px 4px'
                  : '0 14px 12px',
              boxSizing: 'border-box',
              minWidth: 0,
            }}
          >
            {columnSearch}
          </div>
        ) : null}
        {columnAlert ? (
          <div
            className="anima-vista-datos__column-alert"
            style={{
              flexShrink: 0,
              padding: isMobile ? '0 10px 4px' : '0 14px 8px',
              boxSizing: 'border-box',
              minWidth: 0,
            }}
          >
            {columnAlert}
          </div>
        ) : null}
        <div
          className="anima-vista-datos__column-content"
          style={{
            flex: 1,
            minHeight: 0,
            overflowX: 'hidden',
            overflowY: side === 'left' ? 'hidden' : 'auto',
            WebkitOverflowScrolling: side === 'left' ? undefined : 'touch',
            padding: isMobile
              ? side === 'right'
                ? '0 10px 8px 10px'
                : '10px'
              : side === 'right'
                ? '0 14px 8px 14px'
                : '14px',
            boxSizing: 'border-box',
            ...((side === 'left' || side === 'right')
              ? {
                  display: 'flex',
                  flexDirection: 'column',
                }
              : {}),
            ...(columnContentStyle || {}),
          }}
        >
          {content}
        </div>
      </div>
    );
  };

  const columnsLayout = (
    <div
      className="anima-vista-datos__columns"
      style={{
        display: 'flex',
        flexDirection: isMobile ? 'column' : 'row',
        alignItems: isMobile ? 'stretch' : 'flex-start',
        justifyContent: 'center',
        gap: columnsGap,
        padding: isMobile ? 12 : 16,
        boxSizing: 'border-box',
        minWidth: 0,
        ...(columnsContainerStyle || {}),
      }}
    >
      {renderColumnPanel({
        side: 'left',
        columnTitle: leftColumnTitle,
        columnTitleStyle: leftColumnTitleStyle,
        columnAlert: renderLeftColumnAlert(),
        content: renderLeftPanelContent(),
        extraStyle: leftColumnPanelStyle,
      })}
      {renderColumnPanel({
        side: 'right',
        columnTitle: rightColumnTitle,
        columnTitleStyle: rightColumnTitleStyle,
        columnBadge: renderDocumentsBadge(),
        columnSearch: renderRightColumnSearch(),
        content: renderRightPanelContent(),
        extraStyle: rightColumnPanelStyle,
      })}
    </div>
  );
  const hasFileName = Boolean(fileName && String(fileName).trim());
  const headerTitleId = hasFileName ? 'anima-vista-datos-file-name' : undefined;

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

  const handleDownloadReport = () => (onDownloadReportClick ?? onDownloadReport)?.();

  const footerButtonTextStyle = {
    fontSize: '14px',
    lineHeight: '21px',
  };

  const footerButtonBaseStyle = {
    width: 'auto',
    minWidth: 0,
    height: 40,
    padding: '8px 12px',
    marginLeft: 0,
    flexShrink: 0,
  };

  const defaultFooter = (
    <div
      className="anima-vista-datos__footer"
      style={{
        flexShrink: 0,
        padding: isMobile ? '10px 12px' : '12px 16px',
        borderTop: isMobile ? 'none' : '1px solid #E5E7EB',
        background: '#FFFFFF',
        display: 'flex',
        flexDirection: 'row',
        flexWrap: 'nowrap',
        justifyContent: 'flex-end',
        alignItems: 'center',
        gap: 8,
        boxSizing: 'border-box',
        overflowX: 'auto',
        ...(footerStyle || {}),
      }}
    >
      <PrimaryActionButton
        variant="outline"
        text={closeButtonLabel}
        onClick={() => onClose?.()}
        textStyle={{
          ...footerButtonTextStyle,
          ...(closeButtonProps?.textStyle || {}),
        }}
        {...closeButtonProps}
        style={{
          ...footerButtonBaseStyle,
          ...(closeButtonProps?.style || {}),
        }}
      />
      <PrimaryActionButton
        variant="primary"
        text={downloadReportButtonLabel}
        onClick={handleDownloadReport}
        textStyle={{
          ...footerButtonTextStyle,
          ...(downloadReportButtonProps?.textStyle || {}),
        }}
        {...downloadReportButtonProps}
        style={{
          ...footerButtonBaseStyle,
          ...(downloadReportButtonProps?.style || {}),
        }}
      />
    </div>
  );

  return (
    <div
      className={`anima-vista-datos__overlay ${className}`.trim()}
      style={{
        position: 'fixed',
        inset: 0,
        zIndex,
        background: '#00000040',
        opacity: 1,
        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={headerTitleId}
        className="anima-vista-datos__panel"
        onClick={(event) => event.stopPropagation()}
        style={{
          width: isMobile ? '100%' : VISTA_DATOS_DESKTOP_WIDTH_PX,
          maxWidth: '100%',
          height: isMobile
            ? '100%'
            : `min(${VISTA_DATOS_DESKTOP_HEIGHT_PX}px, calc(100vh - 40px))`,
          maxHeight: isMobile ? '100%' : `calc(100vh - 40px)`,
          borderRadius: isMobile ? 0 : 16,
          background: '#FFFFFF',
          border: '1px solid #C4C4C4',
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
          opacity: 1,
          ...style,
          ...panelStyle,
        }}
      >
        <div
          className="anima-vista-datos__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,
          }}
        >
          <div
            className="anima-vista-datos__header-text"
            style={{
              flex: 1,
              minWidth: 0,
              display: 'flex',
              flexDirection: 'column',
              gap: 4,
            }}
          >
            {hasSectionLabel ? (
              <p
                className="anima-vista-datos__section-label"
                style={{
                  ...VISTA_DATOS_SECTION_LABEL_STYLE,
                  ...(sectionLabelStyle || {}),
                }}
              >
                {sectionLabel}
              </p>
            ) : null}
            {hasFileName ? (
              <h2
                id={headerTitleId}
                className="anima-vista-datos__file-name"
                style={{
                  ...VISTA_DATOS_FILE_NAME_STYLE,
                  ...(fileNameStyle || {}),
                }}
              >
                {fileName}
              </h2>
            ) : null}
          </div>
          <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>
        </div>

        <div
          className="anima-vista-datos__body"
          style={{
            flex: 1,
            minHeight: 0,
            overflowY: 'auto',
            overflowX: 'hidden',
            WebkitOverflowScrolling: 'touch',
            overscrollBehavior: 'contain',
            boxSizing: 'border-box',
          }}
        >
          {bodyOverride != null ? bodyOverride : columnsLayout}
        </div>

        {showFooter ? footer ?? defaultFooter : null}
      </div>
    </div>
  );
};

export default VistaDatos;
