/**
 * ListaEmpresas: lista de empresas con título opcional, filas (nombre comercial, país, estado, actividad, acciones) y vista tabla/cards.
 * Reutiliza Typography, Badge, PrimaryActionButton, Icon, FONT_FAMILY_SANS.
 */
import { useState, useMemo, useEffect, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Typography } from '../../Atoms/Typography/Typography';
import { Badge } from '../../Atoms/Badge/Badge';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { Icon } from '../../Atoms/Icon/Icon';
import { CardsEmpresas } from '../CardsEmpresas/CardsEmpresas';
import { MenuAcciones } from '../MenuAcciones/MenuAcciones';
import {
  Tabla,
  TABLA_TOOLBAR_ICONS_DEFAULT,
  RegistrosHastaInput,
} from '../Tabla/Tabla';
import {
  computeRegistrosRangoDesdeHasta,
  computeRegistrosRangoDesdeHastaConPageSize,
  clampRegistrosPorPagina,
  resolvePageAfterPageSizeChange,
} from '../Tabla/tablaRegistrosAndTimeUtils.js';
import { FONT_FAMILY_SANS, FONT_FAMILY_MONO } from '../../../designTokens';

/** Mismo flex y minWidth por defecto en todas las columnas de datos (sin `width` fijo). */
const LISTA_EMPRESAS_TABLA_COL_FLEX = 1;
const LISTA_EMPRESAS_TABLA_COL_MIN_WIDTH = 140;

function getEmpresasTablaColumns(
  t,
  actionButtonText,
  onActionClick,
  deleteActionText,
  onDeleteClick,
  showEditCardButton,
  showDeleteCardButton,
  shouldShowEditCardButton,
  shouldShowDeleteCardButton,
) {
  const getNombreComercialInitials = (value) => {
    const text = (value || '').trim();
    if (!text) return '';
    const words = text.split(/\s+/).filter(Boolean);
    if (words.length >= 2) {
      return `${words[0][0] ?? ''}${words[1][0] ?? ''}`.toUpperCase();
    }
    return `${words[0]?.[0] ?? ''}`.toUpperCase();
  };

  return [
    {
      field: 'nombreComercial',
      headerName: t('empresa.table.header.tradeName', { defaultValue: 'Nombre comercial' }),
      flex: LISTA_EMPRESAS_TABLA_COL_FLEX,
      minWidth: LISTA_EMPRESAS_TABLA_COL_MIN_WIDTH,
      valueGetter: (value, row) => row.nombreComercial ?? row.nombreFantasia ?? '',
      renderCell: (params) => {
        const nombreComercial = params.row?.nombreComercial ?? params.row?.nombreFantasia ?? params.value ?? '';
        if (!nombreComercial) return null;
        const resolveIdentifier = (row) => {
          const rawType =
            row?.legalIdentifier?.type
            ?? row?.legalIdentifierType
            ?? (row?.cuit ? 'CUIT' : '');
          const type = String(rawType || '').trim().toUpperCase() || 'CUIT';

          const rawNumber =
            row?.legalIdentifier?.number
            ?? row?.legalIdentifierNumber
            ?? row?.cuit;
          const number = rawNumber ? String(rawNumber).trim() : '—';

          return `${type}: ${number || '—'}`;
        };

        const identifierLabel = resolveIdentifier(params.row);
        const initials = getNombreComercialInitials(nombreComercial);

        return (
          <div
            style={{
              width: '100%',
              minWidth: 0,
              display: 'flex',
              alignItems: 'center',
              gap: 12,
            }}
          >
            <div
              style={{
                width: 40,
                height: 40,
                minWidth: 40,
                minHeight: 40,
                borderRadius: '999px',
                border: '1px solid var(--color-main-700, #38656D)',
                background: 'var(--color-neutrals-white, #FFFFFF)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                boxSizing: 'border-box',
              }}
            >
              <Typography
                component="span"
                style={{
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 500,
                  fontStyle: 'normal',
                  fontSize: '14px',
                  lineHeight: '100%',
                  letterSpacing: '0px',
                  color: 'var(--color-main-700, #38656D)',
                  margin: 0,
                }}
              >
                {initials}
              </Typography>
            </div>
            <div
              style={{
                minWidth: 0,
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
              }}
            >
              <Typography
                component="span"
                style={{
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 600,
                  fontStyle: 'normal',
                  fontSize: '16px',
                  lineHeight: '24px',
                  letterSpacing: '0%',
                  color: 'var(--color-main-800, #29474C)',
                  margin: 0,
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}
              >
                {nombreComercial}
              </Typography>
              <Typography
                component="span"
                style={{
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 400,
                  fontStyle: 'normal',
                  fontSize: '14px',
                  lineHeight: '21px',
                  letterSpacing: '0.01em',
                  color: 'var(--color-main-800, #29474C)',
                  margin: 0,
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}
              >
                {identifierLabel}
              </Typography>
            </div>
          </div>
        );
      },
    },
    {
      field: 'pais',
      headerName: t('empresa.table.header.country', { defaultValue: 'País' }),
      flex: LISTA_EMPRESAS_TABLA_COL_FLEX,
      minWidth: LISTA_EMPRESAS_TABLA_COL_MIN_WIDTH,
    },
    {
      field: 'estado',
      headerName: t('empresa.table.header.status', { defaultValue: 'Estado' }),
      flex: LISTA_EMPRESAS_TABLA_COL_FLEX,
      minWidth: LISTA_EMPRESAS_TABLA_COL_MIN_WIDTH,
      valueGetter: (value, row) => row.estado ?? row.status ?? '',
      renderCell: (params) => {
        const estadoText = params.row?.estado ?? params.row?.status ?? params.value ?? '';
        if (!estadoText) return null;
        const statusVariant = params.row?.statusVariant
          || DEFAULT_STATUS_VARIANT[params.row?.estado ?? params.row?.status]
          || DEFAULT_STATUS_VARIANT[params.row?.status]
          || 'default';
        return (
          <Badge variant={statusVariant} size="medium">
            {estadoText}
          </Badge>
        );
      },
    },
    {
      field: 'actividad',
      headerName: t('empresa.table.header.activity', { defaultValue: 'Actividad' }),
      flex: LISTA_EMPRESAS_TABLA_COL_FLEX,
      minWidth: LISTA_EMPRESAS_TABLA_COL_MIN_WIDTH,
    },
    {
      field: 'acciones',
      headerName: t('empresa.table.header.actions', { defaultValue: 'Acciones' }),
      flex: LISTA_EMPRESAS_TABLA_COL_FLEX,
      minWidth: LISTA_EMPRESAS_TABLA_COL_MIN_WIDTH,
      sortable: false,
      filterable: false,
      disableColumnMenu: true,
      renderCell: (params) => {
        let index = 0;
        try {
          if (params.api && typeof params.api.getRowIndex === 'function') {
            index = params.api.getRowIndex(params.id);
          }
        } catch (_) {}
        const isEditVisible = typeof shouldShowEditCardButton === 'function'
          ? !!shouldShowEditCardButton(params.row, index)
          : showEditCardButton;
        const isDeleteVisible = typeof shouldShowDeleteCardButton === 'function'
          ? !!shouldShowDeleteCardButton(params.row, index)
          : showDeleteCardButton;

        return (
          <MenuAcciones
            ariaLabel={t('table.actionsAria', { defaultValue: 'Acciones' })}
            menuWidth={isDeleteVisible ? 116 : 102}
            actions={[
              ...(isEditVisible && actionButtonText
                ? [{
                    key: 'edit',
                    icon: 'PencilSquareIcon',
                    label: actionButtonText,
                    onClick: (event) => onActionClick?.(params.row, index, event),
                  }]
                : []),
              ...(isDeleteVisible && deleteActionText
                ? [{
                    key: 'delete',
                    icon: 'TrashIcon',
                    label: deleteActionText,
                    onClick: (event) => onDeleteClick?.(params.row, index, event),
                  }]
                : []),
            ]}
          />
        );
      },
    },
  ];
}

const toolbarStyles = `
  .anima-listaempresas__toolbar-btn--with-border {
    border: 1px solid var(--color-main-700, #38656D) !important;
  }
  .anima-listaempresas__toolbar-btn--with-border:active {
    background: var(--color-main-700, #38656D) !important;
  }
  .anima-listaempresas__toolbar-btn--with-border:active .anima-listaempresas__toolbar-btn-icon {
    color: var(--color-neutrals-white, #FFFFFF) !important;
  }
  .anima-listaempresas__toolbar-btn--selected,
  .anima-listaempresas__toolbar-btn--with-border.anima-listaempresas__toolbar-btn--selected {
    background: var(--color-main-700, #38656D) !important;
    border: 1px solid var(--color-main-700, #38656D) !important;
  }
  .anima-listaempresas__toolbar-btn--selected .anima-listaempresas__toolbar-btn-icon {
    color: var(--color-neutrals-white, #FFFFFF) !important;
  }
  .anima-listaempresas__search-input::placeholder {
    font-family: var(--font-family-sans);
    font-weight: 400;
    font-style: italic;
    font-size: 16px;
    line-height: 24px;
    color: var(--color-grey-700, #474747);
    opacity: 1;
  }
  /* Más aire cuando ListaEmpresas muestra la Tabla */
  .anima-listaempresas .anima-tabla__search-wrap {
    margin-bottom: 20px !important;
  }
  .anima-listaempresas .anima-tabla__red-bar {
    margin-bottom: 12px !important;
  }
  .anima-listaempresas .anima-tabla__grid .MuiDataGrid-cell {
    padding-top: 14px !important;
    padding-bottom: 14px !important;
  }
  .anima-listaempresas .anima-tabla__grid .MuiDataGrid-columnHeader {
    padding-top: 14px !important;
    padding-bottom: 14px !important;
  }
  .anima-listaempresas .anima-tabla__grid .MuiDataGrid-columnHeader,
  .anima-listaempresas .anima-tabla__grid .MuiDataGrid-cell {
    border-right: none !important;
  }
  .anima-listaempresas .anima-tabla__grid .MuiDataGrid-cell {
    border-bottom: none !important;
  }
  .anima-listaempresas .anima-tabla__grid .MuiDataGrid-columnHeaders {
    border-bottom: none !important;
  }
  .anima-listaempresas .anima-tabla__grid .MuiDataGrid-cell[data-field="acciones"] {
    overflow: visible !important;
  }
`;

const COLOR_MAIN = 'var(--color-cyan-19, #29474C)';
const COLOR_SECONDARY = 'var(--color-gray-600, #4b5563)';
const BORDER_COLOR = '#C4C4C4';
const LISTA_EMPRESAS_PAGE_SIZE_DEFAULT = 10;

/** Mapeo status texto → variante Badge por defecto */
const DEFAULT_STATUS_VARIANT = {
  Borrador: 'primary',
  Activa: 'success',
  Activo: 'success',
  Inactiva: 'inactive',
  Inactivo: 'inactive',
  Suspendida: 'error',
  Error: 'error',
};

/** Items: { id, nombreComercial?|nombreFantasia?, pais?, estado?|status?, actividad?, ... } */
export const ListaEmpresas = ({
  /** Título de la lista (ej. "Empresas") */
  title = 'Empresas',
  showTitle = true,
  /** Array de items: { id, nombreComercial?|nombreFantasia?, pais?, estado?|status?, actividad?, ... } */
  items = [],
  /** Callback al hacer clic en la fila: (item, index) => void */
  onItemClick,
  /** Texto del botón de acción por fila (ej. "Editar"). Si no se pasa, no se muestra botón. */
  actionButtonText = '',
  /** Callback del botón de acción: (item, index, event) => void */
  onActionClick,
  /** Texto del botón de eliminar en cards */
  deleteActionText = 'Eliminar',
  /** Callback del botón eliminar en cards: (item, index, event) => void */
  onDeleteClick,
  /** Mostrar/ocultar acciones en cards de forma global */
  showEditCardButton = true,
  showDeleteCardButton = true,
  /** Mostrar/ocultar acciones por ítem en cards */
  shouldShowEditCardButton,
  shouldShowDeleteCardButton,
  /** Mensaje o nodo cuando items.length === 0 */
  emptyMessage = 'No hay empresas cargadas.',
  /** Renderizado custom por item: (item, index) => ReactNode. Si se pasa, reemplaza la fila por defecto. */
  renderItem,
  /** Búsqueda: valor controlado */
  searchValue,
  /** Callback cambio búsqueda: (value, event) => void */
  onSearchChange,
  /** Placeholder del input de búsqueda */
  searchPlaceholder,
  /** Registros visibles en página (para “Registros: N de total”) */
  registrosCurrent,
  /** Total de registros */
  tableTotalCount,
  /** Rango real explícito (1-based) */
  registrosRangoDesde,
  registrosRangoHasta,
  /** Tamaño real de página para cálculo de rango */
  pageSize,
  /** Página actual */
  currentPage: currentPageProp,
  /** Total de páginas */
  totalPages: totalPagesProp,
  /** Acción página anterior */
  onPrevPage,
  /** Acción página siguiente */
  onNextPage,
  /** Paginación controlada: ir a una página concreta (p. ej. al cambiar registros por página). */
  onPageChange,
  /** Con paginación controlada: nuevo tamaño de página tras editar el número central (ver `clampRegistrosPorPagina`). */
  onPageSizeChange,
  /** Si true, muestra skeleton de carga en la vista tabla */
  tableLoading = false,
  className = '',
  style = {},
  titleStyle = {},
  listStyle = {},
  itemClassName = '',
  itemStyle = {},
  ...props
}) => {
  const { t } = useTranslation();
  const [viewMode, setViewMode] = useState('tabla'); // 'lista' | 'tabla' | 'cards'
  const [internalPage, setInternalPage] = useState(1);
  const [internalPageSize, setInternalPageSize] = useState(LISTA_EMPRESAS_PAGE_SIZE_DEFAULT);

  const empresasTablaColumns = useMemo(
    () => getEmpresasTablaColumns(
      t,
      actionButtonText,
      onActionClick,
      deleteActionText,
      onDeleteClick,
      showEditCardButton,
      showDeleteCardButton,
      shouldShowEditCardButton,
      shouldShowDeleteCardButton,
    ),
    [
      t,
      actionButtonText,
      onActionClick,
      deleteActionText,
      onDeleteClick,
      showEditCardButton,
      showDeleteCardButton,
      shouldShowEditCardButton,
      shouldShowDeleteCardButton,
    ]
  );

  const getStatusVariant = (item) => {
    if (item.statusVariant) return item.statusVariant;
    return DEFAULT_STATUS_VARIANT[item.estado ?? item.status] || DEFAULT_STATUS_VARIANT[item.status] || 'default';
  };
  const totalRegistros = items.length;
  const totalRegistrosLabel =
    tableTotalCount !== undefined && tableTotalCount !== null ? tableTotalCount : totalRegistros;
  const isPaginationControlled =
    typeof currentPageProp === 'number' ||
    typeof totalPagesProp === 'number' ||
    typeof onPrevPage === 'function' ||
    typeof onNextPage === 'function' ||
    registrosCurrent !== undefined ||
    tableTotalCount !== undefined;

  const currentPage = isPaginationControlled ? (currentPageProp ?? 1) : internalPage;
  const rawPageSize = isPaginationControlled ? (pageSize ?? internalPageSize) : internalPageSize;
  const effectivePageSize =
    totalRegistrosLabel > 0
      ? clampRegistrosPorPagina(rawPageSize, totalRegistrosLabel)
      : rawPageSize;

  useEffect(() => {
    if (isPaginationControlled || totalRegistrosLabel <= 0) return;
    const next = clampRegistrosPorPagina(internalPageSize, totalRegistrosLabel);
    if (next !== internalPageSize) setInternalPageSize(next);
  }, [isPaginationControlled, totalRegistrosLabel, internalPageSize]);
  const totalPages = isPaginationControlled
    ? (totalPagesProp ?? 1)
    : Math.max(1, Math.ceil(totalRegistros / effectivePageSize));

  const startIndex = isPaginationControlled ? 0 : (currentPage - 1) * effectivePageSize;
  const itemsForRender = isPaginationControlled
    ? items
    : items.slice(startIndex, startIndex + effectivePageSize);

  const registrosN =
    registrosCurrent !== undefined && registrosCurrent !== null
      ? registrosCurrent
      : itemsForRender.length;
  const registrosRango = useMemo(() => {
    const hasExplicitRange =
      Number.isFinite(registrosRangoDesde) && Number.isFinite(registrosRangoHasta);
    if (hasExplicitRange) {
      return { desde: registrosRangoDesde, hasta: registrosRangoHasta };
    }
    if (Number.isFinite(effectivePageSize) && effectivePageSize > 0) {
      return computeRegistrosRangoDesdeHastaConPageSize({
        sinContenido: items.length === 0,
        totalRegistrosLabel,
        registrosEnPagina: registrosN,
        currentPage,
        pageSize: effectivePageSize,
      });
    }
    return computeRegistrosRangoDesdeHasta({
      sinContenido: items.length === 0,
      totalRegistrosLabel,
      registrosEnPagina: registrosN,
      currentPage,
      totalPages,
    });
  }, [
    items.length,
    totalRegistrosLabel,
    registrosN,
    currentPage,
    totalPages,
    registrosRangoDesde,
    registrosRangoHasta,
    effectivePageSize,
  ]);
  const hasPrevPage = currentPage > 1;
  const hasNextPage = currentPage < totalPages;

  const handlePrevPage = () => {
    if (isPaginationControlled) {
      onPrevPage?.();
    } else {
      setInternalPage((p) => Math.max(1, p - 1));
    }
  };

  const handleNextPage = () => {
    if (isPaginationControlled) {
      onNextPage?.();
    } else {
      setInternalPage((p) => Math.min(totalPages, p + 1));
    }
  };

  const canEditPageSize = !isPaginationControlled || typeof onPageSizeChange === 'function';

  const handleRegistrosPorPaginaCommit = useCallback(
    (rawNext) => {
      const clamped = clampRegistrosPorPagina(rawNext, totalRegistrosLabel);
      if (clamped === 0 || totalRegistrosLabel === 0) return;
      const newPage = resolvePageAfterPageSizeChange({
        currentPage,
        previousPageSize: effectivePageSize,
        nextPageSize: clamped,
        totalRegistrosLabel,
      });
      if (isPaginationControlled) {
        onPageSizeChange?.(clamped);
        onPageChange?.(newPage);
      } else {
        setInternalPageSize(clamped);
        setInternalPage(newPage);
      }
    },
    [
      totalRegistrosLabel,
      effectivePageSize,
      currentPage,
      isPaginationControlled,
      onPageSizeChange,
      onPageChange,
    ],
  );

  const registrosPorPaginaLabel = useMemo(() => {
    if (items.length === 0 || totalRegistrosLabel === 0) return 0;
    if (registrosRango.desde === 0 && registrosRango.hasta === 0) return 0;
    if (Number.isFinite(effectivePageSize) && effectivePageSize > 0) return effectivePageSize;
    return Math.max(1, registrosRango.hasta - registrosRango.desde + 1);
  }, [
    items.length,
    totalRegistrosLabel,
    effectivePageSize,
    registrosRango.desde,
    registrosRango.hasta,
  ]);

  return (
    <div
      className={`anima-listaempresas ${className}`}
      style={{ ...style }}
      {...props}
    >
      <style>{toolbarStyles}</style>
      {/* Vista tabla: componente Tabla completo (búsqueda + iconos + rejilla) */}
      {viewMode === 'tabla' ? (
        <div style={{ padding: 0, border: 'none', overflow: 'visible' }}>
          <Tabla
            users={itemsForRender}
            tableColumns={empresasTablaColumns}
            searchPlaceholder={searchPlaceholder ?? t('empresa.table.searchPlaceholder', { defaultValue: 'Buscar empresas' })}
            searchValue={searchValue}
            onSearchChange={onSearchChange}
            tableLoading={tableLoading}
            sinContenido={items.length === 0}
            emptyStateLabel={emptyMessage}
            registrosCurrent={registrosN}
            tableTotalCount={totalRegistrosLabel}
            registrosRangoDesde={registrosRangoDesde}
            registrosRangoHasta={registrosRangoHasta}
            pageSize={effectivePageSize}
            currentPage={currentPage}
            totalPages={totalPages}
            onPrevPage={handlePrevPage}
            onNextPage={handleNextPage}
            onRegistrosPorPaginaCommit={canEditPageSize ? handleRegistrosPorPaginaCommit : undefined}
            toolbarIcons={[
              { ...TABLA_TOOLBAR_ICONS_DEFAULT[0], onClick: () => {} },
              { ...TABLA_TOOLBAR_ICONS_DEFAULT[1], onClick: () => setViewMode('lista'), selected: true },
              { ...TABLA_TOOLBAR_ICONS_DEFAULT[2], href: undefined, onClick: () => setViewMode('cards'), ariaLabel: 'Cards empresas' },
            ]}
            rowHeight={72}
            containerStyle={{ border: 'none', borderRadius: 0, minHeight: 0 }}
          />
        </div>
      ) : (
        <>
      {/* Barra búsqueda + iconos cuando vista lista o cards */}
      <div
        className="anima-listaempresas__toolbar-wrap"
        style={{
          flexShrink: 0,
          width: '100%',
          padding: '0 0 20px 0',
          borderBottom: viewMode === 'cards' ? 'none' : `1px solid ${BORDER_COLOR}`,
          boxSizing: 'border-box',
          display: 'flex',
          alignItems: 'center',
          gap: 12,
        }}
      >
        <div
          style={{
            flex: '1 1 auto',
            minWidth: 0,
            maxWidth: 498,
            height: 40,
            display: 'flex',
            alignItems: 'center',
            gap: 8,
            paddingLeft: 12,
            paddingRight: 12,
            boxSizing: 'border-box',
            border: '1px solid var(--color-grey-600, #5F5F5F)',
            borderRadius: 8,
            backgroundColor: 'var(--color-neutrals-white, #FFFFFF)',
          }}
        >
          <Icon
            name="MagnifyingGlassCircleIcon"
            size={24}
            style={{ flexShrink: 0, color: 'var(--color-grey-500, #777777)' }}
          />
          <input
            type="search"
            placeholder={searchPlaceholder ?? t('empresa.table.searchPlaceholder', { defaultValue: 'Buscar empresas' })}
            value={searchValue ?? ''}
            onChange={onSearchChange ? (e) => onSearchChange(e.target.value, e) : undefined}
            className="anima-listaempresas__search-input"
            style={{
              flex: 1,
              minWidth: 0,
              height: '100%',
              border: 'none',
              outline: 'none',
              background: 'transparent',
              fontFamily: FONT_FAMILY_SANS,
              fontSize: 16,
              lineHeight: 24,
              boxSizing: 'border-box',
            }}
          />
        </div>
        <div
          className="anima-listaempresas__toolbar-icons"
          style={{
            flexShrink: 0,
            marginLeft: 'auto',
            display: 'flex',
            alignItems: 'center',
            gap: 12,
            boxSizing: 'border-box',
          }}
        >
          {[
            { iconName: 'ArrowDownTrayIcon', ariaLabel: 'Descargar', isLastTwo: false },
            { iconName: 'TableCellsIcon', ariaLabel: 'Vista tabla', isLastTwo: true, onClick: () => setViewMode('tabla') },
            { iconName: 'Squares2X2Icon', ariaLabel: 'Cards empresas', isLastTwo: true, onClick: () => setViewMode('cards') },
          ].map((item, index) => {
            const { iconName, ariaLabel, isLastTwo, onClick } = item;
            const isSelected = (index === 1 && viewMode === 'tabla') || (index === 2 && viewMode === 'cards');
            const Wrapper = onClick ? 'button' : 'div';
            return (
              <Wrapper
                key={index}
                type={Wrapper === 'button' ? 'button' : undefined}
                onClick={onClick}
                aria-label={ariaLabel}
                aria-pressed={isSelected || undefined}
                className={`anima-listaempresas__toolbar-btn ${isLastTwo ? 'anima-listaempresas__toolbar-btn--with-border' : ''} ${isSelected ? 'anima-listaempresas__toolbar-btn--selected' : ''}`.trim()}
                style={{
                  width: 48,
                  height: 40,
                  paddingTop: 8,
                  paddingRight: 12,
                  paddingBottom: 8,
                  paddingLeft: 12,
                  borderRadius: 8,
                  opacity: 1,
                  boxSizing: 'border-box',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  border: 'none',
                  background: 'transparent',
                  cursor: onClick ? 'pointer' : 'default',
                }}
              >
                <Icon
                  name={iconName}
                  variant="24-outline"
                  size={24}
                  className="anima-listaempresas__toolbar-btn-icon"
                  style={{ flexShrink: 0, color: 'var(--color-grey-600, #5F5F5F)' }}
                />
              </Wrapper>
            );
          })}
        </div>
      </div>
      {showTitle && title && viewMode === 'lista' && (
        <div
          style={{
            padding: '24px 24px 16px 24px',
            borderBottom: items.length > 0 ? `1px solid ${BORDER_COLOR}` : 'none',
            boxSizing: 'border-box',
            ...titleStyle,
          }}
        >
          <Typography
            variant="h6"
            weight="regular"
            style={{
              fontFamily: FONT_FAMILY_SANS,
              fontWeight: 400,
              fontSize: '20px',
              lineHeight: '30px',
              letterSpacing: '0%',
              color: COLOR_MAIN,
              margin: 0,
            }}
          >
            {title}
          </Typography>
        </div>
      )}

      {viewMode === 'cards' ? (
        <div style={{ padding: 0, boxSizing: 'border-box' }}>
          <div
            style={{
              width: '100%',
              minHeight: '21px',
              marginBottom: '12px',
              boxSizing: 'border-box',
              display: 'flex',
              alignItems: 'stretch',
              flexWrap: 'nowrap',
            }}
          >
            <div
              style={{
                flex: 1,
                minWidth: 0,
                display: 'flex',
                alignItems: 'center',
                paddingLeft: '8px',
                overflow: 'hidden',
              }}
            >
              <span
                style={{
                  fontFamily: FONT_FAMILY_MONO,
                  fontWeight: 500,
                  fontStyle: 'normal',
                  fontSize: '14px',
                  lineHeight: '21px',
                  letterSpacing: '0.01em',
                  verticalAlign: 'middle',
                  color: 'var(--color-grey-600, #5F5F5F)',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  display: 'block',
                }}
              >
                {t('table.recordsPrefix', { defaultValue: 'Registros:' })}{' '}
                <RegistrosHastaInput
                  registrosPorPagina={registrosPorPaginaLabel}
                  totalRegistrosLabel={totalRegistrosLabel}
                  onCommit={canEditPageSize ? handleRegistrosPorPaginaCommit : undefined}
                  disabled={items.length === 0 || !canEditPageSize}
                />
                {' '}
                {t('table.of', { defaultValue: 'de' })}{' '}
                {totalRegistrosLabel}
              </span>
            </div>
            <div
              style={{
                width: 'auto',
                flexShrink: 0,
                flex: '0 0 auto',
                boxSizing: 'border-box',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'flex-end',
                paddingRight: '8px',
                gap: '8px',
                minHeight: '21px',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <span
                  style={{
                    fontFamily: FONT_FAMILY_MONO,
                    fontWeight: 500,
                    fontSize: '14px',
                    lineHeight: '21px',
                    letterSpacing: '0.01em',
                    color: 'var(--color-grey-600, #5F5F5F)',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {t('table.pagePrefix', { defaultValue: 'Página' })}{' '}
                  <span style={{ fontWeight: 700 }}>{currentPage}</span>
                  {` ${t('table.of', { defaultValue: 'de' })} ${totalPages}`}
                </span>
              </div>
              &nbsp;
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <button
                  type="button"
                  disabled={!hasPrevPage}
                  onClick={handlePrevPage}
                  aria-label={t('table.prevPageAria', { defaultValue: 'Página anterior' })}
                  style={{
                    padding: 0,
                    border: 'none',
                    background: 'none',
                    cursor: hasPrevPage ? 'pointer' : 'default',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Icon
                    name="ChevronDoubleLeftIcon"
                    size={14}
                    style={{
                      width: 12,
                      height: 14,
                      opacity: 1,
                      color: hasPrevPage ? 'var(--color-main-700, #38656D)' : 'var(--color-main-400, #84A0A5)',
                    }}
                  />
                </button>
                <button
                  type="button"
                  disabled={!hasNextPage}
                  onClick={handleNextPage}
                  aria-label={t('table.nextPageAria', { defaultValue: 'Página siguiente' })}
                  style={{
                    padding: 0,
                    border: 'none',
                    background: 'none',
                    cursor: hasNextPage ? 'pointer' : 'default',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Icon
                    name="ChevronDoubleRightIcon"
                    size={14}
                    style={{
                      width: 12,
                      height: 14,
                      opacity: 1,
                      color: hasNextPage ? 'var(--color-main-700, #38656D)' : 'var(--color-main-400, #84A0A5)',
                    }}
                  />
                </button>
              </div>
            </div>
          </div>
          <CardsEmpresas
            items={itemsForRender}
            loading={tableLoading}
            onItemClick={onItemClick}
            actionButtonText={actionButtonText}
            onActionClick={onActionClick}
            deleteActionText={deleteActionText}
            onDeleteClick={onDeleteClick}
            showEditButton={showEditCardButton}
            showDeleteButton={showDeleteCardButton}
            shouldShowEditButton={shouldShowEditCardButton}
            shouldShowDeleteButton={shouldShowDeleteCardButton}
            emptyMessage={emptyMessage}
          />
        </div>
      ) : items.length === 0 ? (
        <div
          style={{
            padding: 32,
            textAlign: 'center',
            fontFamily: FONT_FAMILY_SANS,
            fontSize: '16px',
            lineHeight: '24px',
            color: COLOR_SECONDARY,
          }}
        >
          {emptyMessage}
        </div>
      ) : (
        <ul
          className="anima-listaempresas__list"
          style={{
            margin: 0,
            padding: 0,
            listStyle: 'none',
            ...listStyle,
          }}
        >
          {itemsForRender.map((item, index) => (
            <li
              key={item.id ?? index}
              className={`anima-listaempresas__item ${itemClassName}`}
              style={{
                borderBottom: index < items.length - 1 ? `1px solid ${BORDER_COLOR}` : 'none',
                padding: '16px 24px',
                boxSizing: 'border-box',
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                gap: 16,
                cursor: onItemClick ? 'pointer' : undefined,
                ...itemStyle,
              }}
              onClick={onItemClick ? () => onItemClick(item, index) : undefined}
              onKeyDown={
                onItemClick
                  ? (e) => {
                      if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        onItemClick(item, index);
                      }
                    }
                  : undefined
              }
              role={onItemClick ? 'button' : undefined}
              tabIndex={onItemClick ? 0 : undefined}
            >
              {typeof renderItem === 'function' ? (
                renderItem(item, index)
              ) : (
                <>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <Typography
                      variant="body-lg"
                      style={{
                        fontFamily: FONT_FAMILY_SANS,
                        fontWeight: 500,
                        fontSize: '16px',
                        lineHeight: '24px',
                        letterSpacing: 0,
                        color: COLOR_MAIN,
                        margin: 0,
                      }}
                    >
                      {(item.nombreComercial ?? item.nombreFantasia)}
                    </Typography>
                    {(item.actividad ?? item.razonSocial) && (
                      <Typography
                        variant="body-md"
                        style={{
                          fontFamily: FONT_FAMILY_SANS,
                          fontWeight: 400,
                          fontSize: '14px',
                          lineHeight: '21px',
                          letterSpacing: '0%',
                          color: COLOR_SECONDARY,
                          margin: '4px 0 0 0',
                        }}
                      >
                        {(item.actividad ?? item.razonSocial)}
                      </Typography>
                    )}
                  </div>
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'row',
                      alignItems: 'center',
                      gap: 12,
                      flexShrink: 0,
                    }}
                  >
                    {(item.estado ?? item.status) && (
                      <Badge variant={getStatusVariant(item)} size="medium">
                        {item.estado ?? item.status}
                      </Badge>
                    )}
                    {actionButtonText && (
                      <PrimaryActionButton
                        variant="outline"
                        text={actionButtonText}
                        onClick={(e) => {
                          e?.stopPropagation?.();
                          onActionClick?.(item, index, e);
                        }}
                        type="button"
                      />
                    )}
                  </div>
                </>
              )}
            </li>
          ))}
        </ul>
      )}
        </>
      )}
    </div>
  );
};

export default ListaEmpresas;
