import { Icon } from '../../Atoms/Icon/Icon';
import {
  VISTA_DATOS_DETALLE_DIVIDER_STYLE,
  VISTA_DATOS_DETALLE_EMPRESA_ICON_BOX_STYLE,
  VISTA_DATOS_DETALLE_EMPRESA_NOMBRE_STYLE,
  VISTA_DATOS_DETALLE_ROW_LABEL_STYLE,
  VISTA_DATOS_DETALLE_ROW_VALUE_STYLE,
  VISTA_DATOS_DETALLE_STAT_LABEL_STYLE,
  VISTA_DATOS_DETALLE_STAT_VALUE_STYLE,
  VISTA_DATOS_DETALLE_MAIN_STYLE,
  VISTA_DATOS_DETALLE_STATS_DIVIDER_STYLE,
  VISTA_DATOS_DETALLE_STATS_GRID_STYLE,
  VISTA_DATOS_DETALLE_STATS_WRAP_STYLE,
} from './vistaDatosDetalleStyles';
import { VISTA_DATOS_DETALLE_DEFAULTS } from './vistaDatosDetalleDefaults';

const AVATAR_SIZE_PX = 40;

function DetalleDivider() {
  return <hr className="anima-vista-datos-detalle__divider" style={VISTA_DATOS_DETALLE_DIVIDER_STYLE} />;
}

function DetalleMetadataRow({ label, value, labelStyle, valueStyle, isNarrow = false }) {
  if (!label && !value) return null;
  const valueNarrowStyle = isNarrow ? { maxWidth: '58%', textAlign: 'right' } : {};

  return (
    <div
      className="anima-vista-datos-detalle__row"
      style={{
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
        gap: isNarrow ? 8 : 16,
        width: '100%',
        maxWidth: '100%',
        boxSizing: 'border-box',
      }}
    >
      <span style={{ ...VISTA_DATOS_DETALLE_ROW_LABEL_STYLE, ...(labelStyle || {}) }}>{label}</span>
      <span
        style={{
          ...VISTA_DATOS_DETALLE_ROW_VALUE_STYLE,
          ...valueNarrowStyle,
          ...(valueStyle || {}),
        }}
      >
        {value}
      </span>
    </div>
  );
}

function DetalleMetadataSection({
  rows,
  showDividerAfter = true,
  rowLabelStyle,
  rowValueStyle,
  isNarrow = false,
}) {
  const validRows = (rows ?? []).filter((row) => row && (row.label || row.value));
  if (validRows.length === 0) return null;

  return (
    <>
      <div
        className="anima-vista-datos-detalle__section"
        style={{ display: 'flex', flexDirection: 'column', gap: 10, width: '100%' }}
      >
        {validRows.map((row, index) => (
          <DetalleMetadataRow
            key={row.id ?? `${row.label}-${index}`}
            label={row.label}
            value={row.value}
            labelStyle={row.labelStyle ?? rowLabelStyle}
            valueStyle={row.valueStyle ?? rowValueStyle}
            isNarrow={isNarrow}
          />
        ))}
      </div>
      {showDividerAfter ? <DetalleDivider /> : null}
    </>
  );
}

/**
 * Contenido de la columna DETALLES: cabecera empresa, metadata y totales.
 * Reutiliza patrones de VistaDocumento (label/valor) y AltaEdicionPersonas (icon box empresa).
 */
export const VistaDatosDetallePanel = ({
  empresaNombre = VISTA_DATOS_DETALLE_DEFAULTS.empresaNombre,
  empresaIconName = VISTA_DATOS_DETALLE_DEFAULTS.empresaIconName,
  avatarSrc = VISTA_DATOS_DETALLE_DEFAULTS.avatarSrc,
  avatarAlt = VISTA_DATOS_DETALLE_DEFAULTS.avatarAlt,
  avatarName,
  avatarNode,
  metadataSections = VISTA_DATOS_DETALLE_DEFAULTS.metadataSections,
  stats = VISTA_DATOS_DETALLE_DEFAULTS.stats,
  empresaNombreStyle,
  empresaIconBoxStyle,
  rowLabelStyle,
  rowValueStyle,
  statValueStyle,
  statLabelStyle,
  className = '',
  style,
  headerStyle,
  statsStyle,
  isNarrow = false,
  ...props
}) => {
  const sections = Array.isArray(metadataSections) ? metadataSections : [];
  const statItems = Array.isArray(stats) ? stats.filter((s) => s != null) : [];
  const sectionsWithRows = sections.filter((section) =>
    (section?.rows ?? []).some((row) => row && (row.label || row.value)),
  );

  const renderAvatar = () => {
    if (avatarNode != null) return avatarNode;
    if (avatarSrc) {
      return (
        <img
          src={avatarSrc}
          alt={avatarAlt || empresaNombre || 'Avatar'}
          style={{
            width: AVATAR_SIZE_PX,
            height: AVATAR_SIZE_PX,
            borderRadius: '50%',
            objectFit: 'cover',
            flexShrink: 0,
          }}
        />
      );
    }
    if (avatarName) {
      const parts = String(avatarName).trim().split(/\s+/);
      const initials =
        parts.length > 1
          ? `${parts[0][0] ?? ''}${parts[parts.length - 1][0] ?? ''}`.toUpperCase()
          : (parts[0]?.[0] ?? '?').toUpperCase();
      return (
        <div
          aria-hidden
          style={{
            width: AVATAR_SIZE_PX,
            height: AVATAR_SIZE_PX,
            borderRadius: '50%',
            background: '#D3DFE1',
            color: '#29474C',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontFamily: VISTA_DATOS_DETALLE_EMPRESA_NOMBRE_STYLE.fontFamily,
            fontWeight: 600,
            fontSize: '14px',
            flexShrink: 0,
          }}
        >
          {initials}
        </div>
      );
    }
    return null;
  };

  return (
    <div
      className={['anima-vista-datos-detalle', className].filter(Boolean).join(' ')}
      style={{
        width: '100%',
        maxWidth: '100%',
        height: '100%',
        minHeight: 0,
        flex: 1,
        boxSizing: 'border-box',
        display: 'flex',
        flexDirection: 'column',
        ...(style || {}),
      }}
      {...props}
    >
      <div className="anima-vista-datos-detalle__main" style={VISTA_DATOS_DETALLE_MAIN_STYLE}>
      <div
        className="anima-vista-datos-detalle__header"
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 12,
          width: '100%',
          paddingBottom: 8,
          boxSizing: 'border-box',
          ...(headerStyle || {}),
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0, flex: 1 }}>
          <div style={{ ...VISTA_DATOS_DETALLE_EMPRESA_ICON_BOX_STYLE, ...(empresaIconBoxStyle || {}) }}>
            <Icon
              name={empresaIconName}
              variant="24-outline"
              size={24}
              style={{ color: '#29474C', flexShrink: 0 }}
              aria-hidden
            />
          </div>
          {empresaNombre ? (
            <h4
              className="anima-vista-datos-detalle__empresa-nombre"
              style={{
                ...VISTA_DATOS_DETALLE_EMPRESA_NOMBRE_STYLE,
                minWidth: 0,
                wordBreak: 'break-word',
                ...(empresaNombreStyle || {}),
              }}
            >
              {empresaNombre}
            </h4>
          ) : null}
        </div>
        {renderAvatar()}
      </div>

      <DetalleDivider />

      {sectionsWithRows.map((section, index) => (
        <DetalleMetadataSection
          key={section.id ?? `section-${index}`}
          rows={section.rows}
          showDividerAfter={index < sectionsWithRows.length - 1}
          rowLabelStyle={rowLabelStyle}
          rowValueStyle={rowValueStyle}
          isNarrow={isNarrow}
        />
      ))}
      </div>

      {statItems.length > 0 ? (
        <div
          className="anima-vista-datos-detalle__stats-wrap"
          style={{
            ...VISTA_DATOS_DETALLE_STATS_WRAP_STYLE,
            ...(statsStyle || {}),
          }}
        >
          <hr
            className="anima-vista-datos-detalle__stats-divider"
            style={VISTA_DATOS_DETALLE_STATS_DIVIDER_STYLE}
          />
          <div
            className="anima-vista-datos-detalle__stats"
            style={{
              ...VISTA_DATOS_DETALLE_STATS_GRID_STYLE,
              width: isNarrow ? '100%' : VISTA_DATOS_DETALLE_STATS_GRID_STYLE.width,
              justifyContent: isNarrow ? 'space-between' : VISTA_DATOS_DETALLE_STATS_GRID_STYLE.justifyContent,
              gap: isNarrow ? 16 : VISTA_DATOS_DETALLE_STATS_GRID_STYLE.gap,
            }}
          >
          {statItems.map((stat, index) => (
            <div
              key={stat.id ?? `stat-${stat.label}-${index}`}
              className="anima-vista-datos-detalle__stat"
              style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                minWidth: 0,
                textAlign: 'center',
              }}
            >
              <p
                style={{
                  ...VISTA_DATOS_DETALLE_STAT_VALUE_STYLE,
                  ...(statValueStyle || {}),
                  ...(stat.valueStyle || {}),
                }}
              >
                {stat.value}
              </p>
              <p
                style={{
                  ...VISTA_DATOS_DETALLE_STAT_LABEL_STYLE,
                  ...(statLabelStyle || {}),
                  ...(stat.labelStyle || {}),
                }}
              >
                {stat.label}
              </p>
            </div>
          ))}
          </div>
        </div>
      ) : null}
    </div>
  );
};

export { VISTA_DATOS_DETALLE_DEFAULTS } from './vistaDatosDetalleDefaults';
export default VistaDatosDetallePanel;
