import { Tabla } from '../Tabla/Tabla';
import { useTranslation } from 'react-i18next';

/**
 * Estilos que aplican cuando Tabla está dentro de ConfiguracionUsuarios:
 * placeholder del search y media queries para móvil / ancho intermedio.
 */
const placeholderStyles = `
  .anima-configuracionusuarios__container .anima-tabla__search-input::placeholder {
    font-family: var(--font-family-sans);
    font-weight: 400;
    font-style: italic;
    font-size: 16px;
    line-height: 24px;
    letter-spacing: 0;
    color: var(--color-grey-700, #474747);
    opacity: 1;
  }
  /* Mobile: dos renglones a la izquierda (Registros, Página), botones a la derecha; tabla justo debajo */
  @media (max-width: 768px) {
    .anima-configuracionusuarios__container {
      flex: 0 0 auto !important;
      min-height: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__middle {
      flex: 0 0 auto !important;
      display: flex !important;
      flex-direction: column !important;
      gap: 0 !important;
      margin: 0 !important;
      padding: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__middle-spacer {
      flex: 0 0 auto !important;
      order: 1 !important;
      min-height: 0 !important;
      height: 0 !important;
      max-height: 0 !important;
      overflow: hidden !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__red-bar {
      order: 2 !important;
      display: grid !important;
      grid-template-columns: 1fr auto !important;
      grid-template-rows: auto auto !important;
      align-items: center !important;
      gap: 1rem 1rem !important;
      height: auto !important;
      min-height: 21px !important;
      padding-top: 1rem !important;
      padding-bottom: 0 !important;
      margin: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__middle-content-wrap {
      flex: 0 0 auto !important;
      order: 4 !important;
      min-height: 0 !important;
      overflow: hidden !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__middle-table-wrap {
      order: 3 !important;
      flex-shrink: 0 !important;
      margin: 0 !important;
      padding: 0 !important;
      margin-top: -1.5rem !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__middle-table-wrap--no-progress {
      margin-top: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__table-progress-wrap {
      order: 3 !important;
      flex-shrink: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__content {
      padding-top: 0 !important;
      padding-bottom: 0 !important;
      min-height: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__bottom-area {
      margin: 0 !important;
      padding: 0 !important;
      margin-top: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__red-bar-registros {
      grid-column: 1 !important;
      grid-row: 1 !important;
      flex: 0 0 auto !important;
      padding-left: 8px !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__red-bar-pagination {
      display: contents !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__red-bar-pagina-text {
      grid-column: 1 !important;
      grid-row: 2 !important;
      padding-left: 8px !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__red-bar-pagination-buttons {
      grid-column: 2 !important;
      grid-row: 1 / -1 !important;
      align-self: center !important;
      display: flex !important;
      align-items: center !important;
      gap: 1rem !important;
      padding-right: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__red-bar-pagination button {
      width: 48px !important;
      height: 48px !important;
      min-width: 48px !important;
      min-height: 48px !important;
      display: flex !important;
      align-items: center !important;
      justify-content: center !important;
      flex-shrink: 0 !important;
      border: 1px solid var(--color-main-700, #38656D) !important;
      border-radius: 12px !important;
    }
  }
  /* Rango intermedio: mantener layout igual a >=1150 */
  @media (min-width: 1069px) and (max-width: 1149px) {
    .anima-configuracionusuarios__container .anima-tabla__middle {
      display: flex !important;
      flex-direction: column !important;
      gap: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__middle-spacer {
      display: block !important;
      order: 1 !important;
      flex: 0 0 24px !important;
      min-height: 24px !important;
      height: 24px !important;
      max-height: 24px !important;
      overflow: hidden !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__red-bar {
      order: 2 !important;
      display: flex !important;
      flex-direction: row !important;
      flex-wrap: nowrap !important;
      align-items: stretch !important;
      height: 21px !important;
      min-height: 21px !important;
      margin: 0 !important;
      padding-top: 0 !important;
      padding-bottom: 0 !important;
      gap: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__red-bar-registros {
      flex: 1 1 auto !important;
      min-width: 0 !important;
      padding-left: 8px !important;
      display: flex !important;
      align-items: center !important;
      overflow: hidden !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__red-bar-pagination {
      width: auto !important;
      flex: 0 0 auto !important;
      display: flex !important;
      align-items: center !important;
      justify-content: flex-end !important;
      padding-right: 8px !important;
      gap: 8px !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__middle-table-wrap {
      order: 3 !important;
      margin-top: 12px !important;
      padding-top: 0 !important;
    }
    .anima-configuracionusuarios__container .anima-tabla__table-progress-wrap {
      order: 4 !important;
      margin-top: 1rem !important;
    }
  }
`;

const TABLA_HEADER_CLASS = 'anima-tabla__grid-header';

/**
 * Parsea una fecha que puede ser string (ISO, DD/MM/YYYY) o Date y devuelve Date o null.
 */
function parseFechaUltimoAcceso(value) {
  if (value == null || value === '') return null;
  if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
  const str = String(value).trim();
  if (!str) return null;
  const iso = new Date(str);
  if (!Number.isNaN(iso.getTime())) return iso;
  const match = str.match(/^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/);
  if (match) {
    const [, d, m, y] = match;
    const parsed = new Date(parseInt(y, 10), parseInt(m, 10) - 1, parseInt(d, 10));
    if (!Number.isNaN(parsed.getTime())) return parsed;
  }
  return null;
}

/**
 * Devuelve el tiempo transcurrido en español: "Hace un momento", "Hace 15 horas", "Ayer", etc.
 */
function tiempoRelativoEnEspanol(fecha) {
  const date = parseFechaUltimoAcceso(fecha);
  if (!date) return '—';
  const now = new Date();
  const diffMs = now - date;
  const diffDias = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  const diffHoras = Math.floor(diffMs / (1000 * 60 * 60));
  const diffMin = Math.floor(diffMs / (1000 * 60));
  const diffSeg = Math.floor(diffMs / 1000);

  if (diffSeg < 60) return 'Hace un momento';
  if (diffMin < 60) return diffMin === 1 ? 'Hace 1 minuto' : `Hace ${diffMin} minutos`;
  if (diffHoras < 24) return diffHoras === 1 ? 'Hace 1 hora' : `Hace ${diffHoras} horas`;
  if (diffDias === 1) return 'Ayer';
  if (diffDias < 7) return `Hace ${diffDias} días`;
  const semanas = Math.floor(diffDias / 7);
  if (semanas === 1) return 'Hace una semana';
  if (semanas < 4) return `Hace ${semanas} semanas`;
  const meses = Math.floor(diffDias / 30);
  if (meses === 1) return 'Hace un mes';
  if (meses < 12) return `Hace ${meses} meses`;
  const anios = Math.floor(diffDias / 365);
  return anios === 1 ? 'Hace un año' : `Hace ${anios} años`;
}

export const DEFAULT_TABLE_COLUMNS = [
  { field: 'administrador', headerName: 'Administrador', flex: 1, minWidth: 80, headerClassName: TABLA_HEADER_CLASS },
  { field: 'email', headerName: 'Email', flex: 1, minWidth: 80, headerClassName: TABLA_HEADER_CLASS },
  { field: 'rolTecnico', headerName: 'Rol técnico', flex: 1, minWidth: 80, headerClassName: TABLA_HEADER_CLASS },
  {
    field: 'ultimoAcceso',
    headerName: 'Último acceso',
    flex: 1,
    minWidth: 80,
    headerClassName: TABLA_HEADER_CLASS,
    renderCell: (params) => tiempoRelativoEnEspanol(params.value),
  },
];

const DEFAULT_TABLE_ROWS = [
  { id: 1, administrador: 'Usuario 1', email: 'usuario1@ejemplo.com', rolTecnico: 'Admin', ultimoAcceso: '01/02/2025' },
  { id: 2, administrador: 'Usuario 2', email: 'usuario2@ejemplo.com', rolTecnico: 'Editor', ultimoAcceso: '28/01/2025' },
  { id: 3, administrador: 'Usuario 3', email: 'usuario3@ejemplo.com', rolTecnico: 'Lector', ultimoAcceso: '15/01/2025' },
];

export const ConfiguracionUsuarios = ({
  children,
  containerStyle,
  containerClassName = '',
  contentContainerStyle,
  contentContainerClassName = '',
  className = '',
  searchValue,
  onSearchChange,
  searchPlaceholder,
  tableLoading = false,
  users = [],
  tableColumns,
  registrosCurrent,
  tableTotalCount,
  currentPage = 1,
  totalPages = 1,
  onPrevPage,
  onNextPage,
  sinContenido = false,
  emptyStateLabel,
  ...props
}) => {
  const { t } = useTranslation();
  return (
    <div
    className={`anima-configuracionusuarios__container ${containerClassName} ${className}`}
    style={{
      width: '100%',
      minWidth: 0,
      minHeight: '289px',
      height: 'auto',
      backgroundColor: 'transparent',
      boxSizing: 'border-box',
      display: 'flex',
      flexDirection: 'column',
      overflow: 'hidden',
      ...(containerStyle || {}),
    }}
    {...props}
  >
    <style>{placeholderStyles}</style>
    <Tabla
      containerStyle={{}}
      contentContainerStyle={contentContainerStyle}
      contentContainerClassName={contentContainerClassName}
      searchValue={searchValue}
      onSearchChange={onSearchChange}
      searchPlaceholder={searchPlaceholder ?? t('table.searchPlaceholder', { defaultValue: 'Buscar dentro de \'Usuarios\'' })}
      tableLoading={tableLoading}
      users={users.length > 0 ? users : DEFAULT_TABLE_ROWS}
      tableColumns={tableColumns ?? DEFAULT_TABLE_COLUMNS}
      registrosCurrent={registrosCurrent}
      tableTotalCount={tableTotalCount}
      currentPage={currentPage}
      totalPages={totalPages}
      onPrevPage={onPrevPage}
      onNextPage={onNextPage}
      sinContenido={sinContenido}
      emptyStateLabel={emptyStateLabel ?? t('table.noData', { defaultValue: 'Sin contenido' })}
      toolbarIcons={[]}
      skeletonRowCount={4}
    >
      {children}
    </Tabla>
    </div>
  );
};

export default ConfiguracionUsuarios;
