import { useState } from 'react';
import { Tabla, DEFAULT_TABLA_COLUMNS, DEFAULT_TABLA_ROWS, TABLA_TOOLBAR_ICONS_DEFAULT } from './Tabla';
import { Filtros } from '../Filtros/Filtros';

const FILTROS_APLICADOS_INITIAL_CONDITIONS = [
  { id: 'documento-contiene', field: 'documento', operator: 'contiene', value: '345' },
  { id: 'persona-contiene', field: 'persona', operator: 'contiene', value: 'Lau' },
  { id: 'legajo-contiene', field: 'legajo', operator: 'contiene', value: '100' },
];

const FILTROS_APLICADOS_EMPTY_CONDITION = {
  id: 'condition-first',
  field: 'documento',
  operator: 'contiene',
  value: '',
};

const FILTROS_APLICADOS_FIELDS = [
  { value: 'documento', label: 'Documento' },
  { value: 'persona', label: 'Persona' },
  { value: 'fechaImportacion', label: 'Fecha de import...', type: 'date' },
  { value: 'periodo', label: 'Periodo', type: 'date' },
  { value: 'periodoMensual', label: 'Periodo (año-mes)', type: 'period' },
  { value: 'fechaNacimiento', label: 'Fecha de nacimiento', type: 'date' },
  { value: 'legajo', label: 'Legajo' },
];

const OPERATORS_BY_FIELD_EXAMPLE = {
  documento: [
    { value: 'contiene', label: 'contiene' },
    { value: 'noContiene', label: 'no contiene' },
  ],
  persona: [
    { value: 'contiene', label: 'contiene' },
    { value: 'noContiene', label: 'no contiene' },
  ],
  periodo: [
    { value: 'between', label: 'entre' },
    { value: 'antesDe', label: 'antes de' },
    { value: 'despuesDe', label: 'después de' },
  ],
  periodoMensual: [
    { value: 'between', label: 'entre' },
    { value: 'igualA', label: 'igual a' },
  ],
  fechaNacimiento: [
    { value: 'between', label: 'entre' },
    { value: 'antesDe', label: 'antes de' },
    { value: 'despuesDe', label: 'después de' },
  ],
};

const FILTROS_APLICADOS_FIELD_LABELS = {
  documento: 'Documento',
  persona: 'Persona',
  fechaImportacion: 'Fecha de import...',
  periodo: 'Periodo',
  periodoMensual: 'Periodo (año-mes)',
  fechaNacimiento: 'Fecha de nacimiento',
  legajo: 'Legajo',
};

const FILTROS_APLICADOS_OPERATOR_LABELS = {
  contiene: 'contiene',
  noContiene: 'no contiene',
  antesDe: 'antes de',
  despuesDe: 'después de',
  igualA: 'igual a',
  between: 'entre',
  entre: 'entre',
};

const getConditionRangeValue = (condition) => {
  if (condition?.value && typeof condition.value === 'object') {
    return {
      from: condition.value.from ?? '',
      to: condition.value.to ?? '',
    };
  }
  return {
    from: condition?.valueFrom ?? '',
    to: condition?.valueTo ?? '',
  };
};

const conditionHasValue = (condition) => {
  if (condition?.value && typeof condition.value === 'object') {
    const rangeValue = getConditionRangeValue(condition);
    return String(rangeValue.from).trim().length > 0 || String(rangeValue.to).trim().length > 0;
  }
  if (condition?.valueFrom !== undefined || condition?.valueTo !== undefined) {
    const rangeValue = getConditionRangeValue(condition);
    return String(rangeValue.from).trim().length > 0 || String(rangeValue.to).trim().length > 0;
  }
  return String(condition?.value ?? '').trim().length > 0;
};

const formatConditionLabel = (condition) => {
  const field = FILTROS_APLICADOS_FIELD_LABELS[condition.field] ?? condition.field;
  const operator = FILTROS_APLICADOS_OPERATOR_LABELS[condition.operator] ?? condition.operator;
  if (condition?.value && typeof condition.value === 'object') {
    const rangeValue = getConditionRangeValue(condition);
    const separator = rangeValue.from && rangeValue.to ? ' - ' : '';
    return `${field} ${operator} ${rangeValue.from}${separator}${rangeValue.to}`.trim();
  }
  if (condition?.valueFrom !== undefined || condition?.valueTo !== undefined) {
    const rangeValue = getConditionRangeValue(condition);
    const separator = rangeValue.from && rangeValue.to ? ' - ' : '';
    return `${field} ${operator} ${rangeValue.from}${separator}${rangeValue.to}`.trim();
  }
  return `${field} ${operator} ${condition.value}`;
};

function buildAppliedFiltersFromPayload(payload) {
  const conditionFilters = Array.isArray(payload?.conditions)
    ? payload.conditions
        .filter((condition) => conditionHasValue(condition))
        .map((condition) => {
          return {
            id: `condition-${condition.id}`,
            type: 'condition',
            conditionId: condition.id,
            label: formatConditionLabel(condition),
          };
        })
    : [];
  const aiFilter = String(payload?.aiValue ?? '').trim();
  return aiFilter ? [{ id: 'ai-filter', type: 'ai', label: `BEE Asist ${aiFilter}` }, ...conditionFilters] : conditionFilters;
}

export default {
  title: 'Layout/Tabla',
  component: Tabla,
  tags: ['autodocs'],
  argTypes: {
    users: { control: 'object', description: 'Filas (array de objetos con id y campos por columna)' },
    tableColumns: { control: false, description: 'Columnas MUI DataGrid; por defecto DEFAULT_TABLA_COLUMNS' },
    tableLoading: { control: 'boolean' },
    sinContenido: { control: 'boolean', description: 'Estado vacío' },
    emptyStateLabel: { control: 'text' },
    searchValue: { control: 'text' },
    searchPlaceholder: { control: 'text' },
    activeFiltersCount: { control: 'number' },
    appliedFilters: { control: 'object', description: 'Array de filtros aplicados: strings u objetos { id, label }' },
    onAppliedFilterRemove: { action: 'appliedFilterRemove' },
    onAppliedFiltersClear: { action: 'appliedFiltersClear' },
    appliedFiltersLabel: { control: 'text' },
    appliedFiltersClearLabel: { control: 'text' },
    registrosCurrent: { control: 'number' },
    tableTotalCount: { control: 'number' },
    currentPage: { control: 'number' },
    totalPages: { control: 'number' },
    onPrevPage: { action: 'prevPage' },
    onNextPage: { action: 'nextPage' },
    onSearchChange: { action: 'search' },
    toolbarIcons: { control: false, description: 'Array de { iconName, onClick?, ariaLabel?, href? }. Si href está definido, el icono es un enlace (p. ej. para redirigir).' },
  },
};

export const Default = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    tableLoading: false,
    sinContenido: false,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    currentPage: 1,
    totalPages: 1,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
    onSearchChange: (value) => console.log('Search', value),
  },
};

export const ConPaginacion = {
  args: {
    users: [
      ...DEFAULT_TABLA_ROWS,
      { id: 4, administrador: 'Usuario 4', email: 'usuario4@ejemplo.com', rolTecnico: 'Lector', ultimoAcceso: '10/01/2025' },
      { id: 5, administrador: 'Usuario 5', email: 'usuario5@ejemplo.com', rolTecnico: 'Admin', ultimoAcceso: '05/01/2025' },
    ],
    tableColumns: DEFAULT_TABLA_COLUMNS,
    currentPage: 2,
    totalPages: 5,
    registrosCurrent: 5,
    tableTotalCount: 47,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
  },
};

export const Loading = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    tableLoading: true,
    currentPage: 1,
    totalPages: 1,
  },
};

export const SinContenido = {
  args: {
    users: [],
    sinContenido: true,
    emptyStateLabel: 'Sin contenido',
    currentPage: 1,
    totalPages: 1,
  },
};

export const ConBusqueda = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: 'Buscar usuario...',
    searchValue: '',
    onSearchChange: (value) => console.log('Search', value),
    currentPage: 1,
    totalPages: 1,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
  },
};

export const ConFiltrosAvanzados = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    currentPage: 1,
    totalPages: 1,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
  },
};

export const ConFiltrosActivos = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    activeFiltersCount: 3,
    currentPage: 1,
    totalPages: 1,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
  },
};

export const FiltrosAplicados = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    currentPage: 1,
    totalPages: 1,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
    filtersAreaContainerStyle: {
      marginTop: '16px',
      marginBottom: '16px',
    },
  },
  render: (args) => {
    const [conditions, setConditions] = useState(FILTROS_APLICADOS_INITIAL_CONDITIONS);
    const [aiValue, setAiValue] = useState('');
    const [appliedFilters, setAppliedFilters] = useState(() =>
      buildAppliedFiltersFromPayload({ conditions: FILTROS_APLICADOS_INITIAL_CONDITIONS, aiValue: '' })
    );

    const clearFilters = () => {
      setConditions([FILTROS_APLICADOS_EMPTY_CONDITION]);
      setAiValue('');
      setAppliedFilters([]);
    };

    const syncAppliedFilters = (nextConditions, nextAiValue) => {
      setAppliedFilters(buildAppliedFiltersFromPayload({ conditions: nextConditions, aiValue: nextAiValue }));
    };

    const handleConditionsChange = (nextConditions) => {
      setConditions(nextConditions);
      syncAppliedFilters(nextConditions, aiValue);
    };

    const handleAiChange = (nextAiValue) => {
      setAiValue(nextAiValue);
      syncAppliedFilters(conditions, nextAiValue);
    };

    const removeAppliedFilter = (filter) => {
      if (filter.type === 'ai') {
        setAiValue('');
        setAppliedFilters((current) => current.filter((item) => item.id !== filter.id));
        return;
      }

      setConditions((current) => {
        const index = current.findIndex((condition) => condition.id === filter.conditionId);
        if (index <= 0) {
          return current.map((condition) =>
            condition.id === filter.conditionId ? { ...condition, value: '' } : condition
          );
        }
        return current.filter((condition) => condition.id !== filter.conditionId);
      });
      setAppliedFilters((current) => current.filter((item) => item.id !== filter.id));
    };

    return (
      <Tabla
        {...args}
        activeFiltersCount={appliedFilters.length}
        appliedFilters={appliedFilters}
        onAppliedFilterRemove={removeAppliedFilter}
        onAppliedFiltersClear={clearFilters}
        onAdvancedFiltersApply={(payload) => {
          setConditions(payload.conditions ?? [FILTROS_APLICADOS_EMPTY_CONDITION]);
          setAiValue(payload.aiValue ?? '');
          setAppliedFilters(buildAppliedFiltersFromPayload(payload));
          console.log('Apply filters', payload);
        }}
        advancedFiltersModalProps={{
          fields: FILTROS_APLICADOS_FIELDS,
          conditions,
          aiValue,
          onConditionsChange: handleConditionsChange,
          onAiChange: handleAiChange,
          onClear: clearFilters,
        }}
      />
    );
  },
};

export const DateBetween_Periodo = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    currentPage: 1,
    totalPages: 1,
  },
  render: (args) => {
    const [conditions, setConditions] = useState([
      { id: 'periodo-between', field: 'periodo', operator: 'between', value: { from: '', to: '' } },
    ]);
    const [aiValue, setAiValue] = useState('');
    return (
      <Tabla
        {...args}
        onAdvancedFiltersApply={(payload) => console.log('Apply filters', payload)}
        advancedFiltersModalProps={{
          fields: FILTROS_APLICADOS_FIELDS,
          conditions,
          aiValue,
          operatorsByField: OPERATORS_BY_FIELD_EXAMPLE,
          onConditionsChange: setConditions,
          onAiChange: setAiValue,
        }}
      />
    );
  },
};

export const Periodo_AnioMes = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    currentPage: 1,
    totalPages: 1,
  },
  render: (args) => {
    const [conditions, setConditions] = useState([
      { id: 'periodo-mensual-igual', field: 'periodoMensual', operator: 'igualA', value: '2026-01' },
    ]);
    const [aiValue, setAiValue] = useState('');
    return (
      <Tabla
        {...args}
        onAdvancedFiltersApply={(payload) => console.log('Apply filters', payload)}
        advancedFiltersModalProps={{
          fields: FILTROS_APLICADOS_FIELDS,
          conditions,
          aiValue,
          operatorsByField: OPERATORS_BY_FIELD_EXAMPLE,
          onConditionsChange: setConditions,
          onAiChange: setAiValue,
        }}
      />
    );
  },
};

export const PeriodoBetween_AnioMes = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    currentPage: 1,
    totalPages: 1,
  },
  render: (args) => {
    const [conditions, setConditions] = useState([
      { id: 'periodo-mensual-between', field: 'periodoMensual', operator: 'between', value: { from: '', to: '' } },
    ]);
    const [aiValue, setAiValue] = useState('');
    return (
      <Tabla
        {...args}
        onAdvancedFiltersApply={(payload) => console.log('Apply filters', payload)}
        advancedFiltersModalProps={{
          fields: FILTROS_APLICADOS_FIELDS,
          conditions,
          aiValue,
          operatorsByField: OPERATORS_BY_FIELD_EXAMPLE,
          onConditionsChange: setConditions,
          onAiChange: setAiValue,
        }}
      />
    );
  },
};

export const DateBetween_FechaNacimiento = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    currentPage: 1,
    totalPages: 1,
  },
  render: (args) => {
    const [conditions, setConditions] = useState([
      { id: 'fecha-nacimiento-between', field: 'fechaNacimiento', operator: 'between', value: { from: '', to: '' } },
    ]);
    const [aiValue, setAiValue] = useState('');
    return (
      <Tabla
        {...args}
        onAdvancedFiltersApply={(payload) => console.log('Apply filters', payload)}
        advancedFiltersModalProps={{
          fields: FILTROS_APLICADOS_FIELDS,
          conditions,
          aiValue,
          operatorsByField: OPERATORS_BY_FIELD_EXAMPLE,
          onConditionsChange: setConditions,
          onAiChange: setAiValue,
        }}
      />
    );
  },
};

export const OperatorsByField = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    currentPage: 1,
    totalPages: 1,
  },
  render: (args) => {
    const [conditions, setConditions] = useState([
      { id: 'operators-by-field-1', field: 'documento', operator: 'contiene', value: '' },
    ]);
    const [aiValue, setAiValue] = useState('');
    return (
      <Tabla
        {...args}
        onAdvancedFiltersApply={(payload) => console.log('Apply filters', payload)}
        advancedFiltersModalProps={{
          fields: FILTROS_APLICADOS_FIELDS,
          conditions,
          aiValue,
          operatorsByField: OPERATORS_BY_FIELD_EXAMPLE,
          onConditionsChange: setConditions,
          onAiChange: setAiValue,
        }}
      />
    );
  },
};

export const AppliedFiltersDateRange = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    currentPage: 1,
    totalPages: 1,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
    filtersAreaContainerStyle: {
      marginTop: '16px',
      marginBottom: '16px',
    },
  },
  render: (args) => {
    const [conditions, setConditions] = useState([
      { id: 'periodo-between', field: 'periodo', operator: 'between', value: { from: '2026-01-01', to: '2026-01-31' } },
      {
        id: 'fecha-nacimiento-between',
        field: 'fechaNacimiento',
        operator: 'between',
        value: { from: '1990-01-01', to: '1990-12-31' },
      },
    ]);
    const [aiValue, setAiValue] = useState('');
    const [appliedFilters, setAppliedFilters] = useState(() =>
      buildAppliedFiltersFromPayload({ conditions, aiValue: '' })
    );
    return (
      <Tabla
        {...args}
        activeFiltersCount={appliedFilters.length}
        appliedFilters={appliedFilters}
        onAppliedFiltersClear={() => setAppliedFilters([])}
        onAdvancedFiltersApply={(payload) => {
          setConditions(payload.conditions ?? []);
          setAiValue(payload.aiValue ?? '');
          setAppliedFilters(buildAppliedFiltersFromPayload(payload));
        }}
        advancedFiltersModalProps={{
          fields: FILTROS_APLICADOS_FIELDS,
          conditions,
          aiValue,
          operatorsByField: OPERATORS_BY_FIELD_EXAMPLE,
          onConditionsChange: (nextConditions) => {
            setConditions(nextConditions);
            setAppliedFilters(buildAppliedFiltersFromPayload({ conditions: nextConditions, aiValue }));
          },
          onAiChange: (nextAiValue) => {
            setAiValue(nextAiValue);
            setAppliedFilters(buildAppliedFiltersFromPayload({ conditions, aiValue: nextAiValue }));
          },
        }}
      />
    );
  },
  parameters: {
    docs: {
      description: {
        story:
          'Migración sugerida: para `type: date` + operador `between`, enviar `value` como objeto `{ from, to }`. Si no se usa `operatorsByField`, el componente mantiene el comportamiento anterior.',
      },
    },
  },
};

export const FiltrosAplicadosCustomArea = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    showFiltersButton: true,
    filtersButtonLabel: 'Filtros',
    activeFiltersCount: 3,
    currentPage: 1,
    totalPages: 1,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
    filtersAreaContainerStyle: {
      marginTop: '16px',
      marginBottom: '16px',
    },
  },
  render: (args) => (
    <Tabla
      {...args}
      appliedFilters={buildAppliedFiltersFromPayload({
        conditions: FILTROS_APLICADOS_INITIAL_CONDITIONS,
        aiValue: '',
      })}
      filtersArea={
        <div
          style={{
            width: '100%',
            padding: '12px',
            border: '1px dashed #6D3856',
            borderRadius: '8px',
            color: '#6D3856',
            fontFamily: 'var(--font-family-sans)',
            boxSizing: 'border-box',
          }}
        >
          Área custom vía filtersArea: este contenido reemplaza los filtros aplicados nativos.
        </div>
      }
    />
  ),
};

export const ConChildren = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    currentPage: 1,
    totalPages: 1,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
  },
  render: (args) => (
    <Tabla {...args}>
      <p style={{ fontFamily: 'var(--font-family-sans)', fontSize: 14, color: 'var(--color-grey-600)' }}>
        Contenido adicional debajo de la tabla (children). Mismo layout que ConfiguracionUsuarios.
      </p>
    </Tabla>
  ),
};

export const ConIconos = {
  args: {
    users: DEFAULT_TABLA_ROWS,
    tableColumns: DEFAULT_TABLA_COLUMNS,
    currentPage: 1,
    totalPages: 1,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
    onSearchChange: (value) => console.log('Search', value),
    toolbarIcons: TABLA_TOOLBAR_ICONS_DEFAULT.map((item, index) =>
      index === 1
        ? { ...item, onClick: () => console.log('Vista tabla (del medio)') }
        : item
    ),
  },
};

export const ConFilaFiltros = {
  args: {
    users: [
      {
        id: 1,
        documentos: 'Recibo de sueldo - Agosto 2026',
        persona: 'Ana Perez Gurgone',
        documento: 'LEG-1002',
        empresa: 'Hexa Corp Solutions',
        periodo: '2026-08',
      },
      {
        id: 2,
        documentos: 'Recibo de sueldo - Julio 2026',
        persona: 'Pedro Sanchez Carmona',
        documento: 'LEG-1003',
        empresa: 'Hexa Corp Solutions',
        periodo: '2026-07',
      },
      {
        id: 3,
        documentos: 'Certificado medico',
        persona: 'Carlos Ruiz',
        documento: 'LEG-1004',
        empresa: 'Hexa Corp Solutions',
        periodo: '2026-04',
      },
      {
        id: 4,
        documentos: 'Politica interna 2026',
        persona: 'Laura Vidal',
        documento: 'LEG-1005',
        empresa: 'Hexa Corp Solutions',
        periodo: '2026-06',
      },
    ],
    tableColumns: [
      { field: 'documentos', headerName: 'Documentos', flex: 1, minWidth: 260 },
      { field: 'persona', headerName: 'Persona', flex: 1, minWidth: 180 },
      { field: 'documento', headerName: 'Documento', flex: 1, minWidth: 140 },
      { field: 'empresa', headerName: 'Empresa', flex: 1, minWidth: 200 },
      { field: 'periodo', headerName: 'Periodo', flex: 1, minWidth: 120 },
    ],
    currentPage: 1,
    totalPages: 4,
    registrosCurrent: 50,
    tableTotalCount: 200,
    searchPlaceholder: 'Buscar documentos, personas, legajos',
    filtersAreaContainerStyle: {
      marginTop: '12px',
      marginBottom: '10px',
    },
  },
  render: (args) => {
    const [tipo, setTipo] = useState('all');
    const [estado, setEstado] = useState('all');
    const [periodo, setPeriodo] = useState('all');
    const [desde, setDesde] = useState('');
    const [hasta, setHasta] = useState('');

    const items = [
      {
        id: 'tipo',
        label: 'Tipo',
        value: tipo,
        onChange: setTipo,
        options: [
          { value: 'all', label: 'Todos' },
          { value: 'recibos', label: 'Recibos' },
          { value: 'contratos', label: 'Contratos' },
          { value: 'certificados', label: 'Certificados' },
          { value: 'otros', label: 'Otros' },
        ],
      },
      {
        id: 'estado',
        label: 'Estado',
        value: estado,
        onChange: setEstado,
        options: [
          { value: 'all', label: 'Todos' },
          { value: 'vigente', label: 'Vigente' },
          { value: 'pendiente', label: 'Pendiente' },
          { value: 'archivado', label: 'Archivado' },
        ],
      },
      {
        id: 'periodo',
        label: 'Periodo',
        value: periodo,
        onChange: setPeriodo,
        options: [
          { value: 'all', label: 'Todos' },
          { value: '30d', label: 'Ultimos 30 dias' },
          { value: '60d', label: 'Ultimos 60 dias' },
          { value: '90d', label: 'Ultimos 90 dias' },
        ],
      },
    ];

    return (
      <Tabla
        {...args}
        filtersArea={
          <Filtros
            items={items}
            filterByLabel="Filtrar por:"
            importationLabel="Importacion"
            dateFromPlaceholder="Desde"
            dateToPlaceholder="Hasta"
            dateFromValue={desde}
            dateToValue={hasta}
            onDateFromChange={setDesde}
            onDateToChange={setHasta}
            mobileBreakpoint={1024}
          />
        }
      />
    );
  },
};

export const ConScrollVerticalExterno = {
  args: {
    users: Array.from({ length: 30 }).map((_, idx) => ({
      id: idx + 1,
      administrador: `Usuario ${idx + 1}`,
      email: `usuario${idx + 1}@ejemplo.com`,
      rolTecnico: idx % 3 === 0 ? 'Admin' : idx % 3 === 1 ? 'Editor' : 'Lector',
      ultimoAcceso: '01/02/2025',
    })),
    tableColumns: DEFAULT_TABLA_COLUMNS,
    tableLoading: false,
    sinContenido: false,
    searchPlaceholder: "Buscar dentro de 'Usuarios'",
    currentPage: 1,
    totalPages: 4,
    registrosCurrent: 50,
    tableTotalCount: 200,
    showExternalVerticalScroll: true,
    externalVerticalScrollViewportHeight: 320,
    debugExternalVerticalScroll: true,
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
    onSearchChange: (value) => console.log('Search', value),
  },
};

export const ConFiltrosYScrollVerticalExterno = {
  args: {
    users: Array.from({ length: 30 }).map((_, idx) => ({
      id: idx + 1,
      documentos: `Documento ${idx + 1}`,
      persona: `Persona ${idx + 1}`,
      documento: `LEG-${1000 + idx}`,
      empresa: idx % 2 === 0 ? 'Hexa Corp Solutions' : 'Nucleus Labs',
      periodo: `2026-${String((idx % 12) + 1).padStart(2, '0')}`,
    })),
    tableColumns: [
      { field: 'documentos', headerName: 'Documentos', flex: 1, minWidth: 220 },
      { field: 'persona', headerName: 'Persona', flex: 1, minWidth: 180 },
      { field: 'documento', headerName: 'Documento', flex: 1, minWidth: 140 },
      { field: 'empresa', headerName: 'Empresa', flex: 1, minWidth: 200 },
      { field: 'periodo', headerName: 'Periodo', flex: 1, minWidth: 120 },
    ],
    tableLoading: false,
    sinContenido: false,
    searchPlaceholder: 'Buscar documentos, personas, legajos',
    currentPage: 1,
    totalPages: 4,
    registrosCurrent: 50,
    tableTotalCount: 200,
    showExternalVerticalScroll: true,
    externalVerticalScrollViewportHeight: 320,
    filtersAreaContainerStyle: {
      marginTop: '12px',
      marginBottom: '10px',
    },
    onPrevPage: () => console.log('Prev'),
    onNextPage: () => console.log('Next'),
    onSearchChange: (value) => console.log('Search', value),
  },
  render: (args) => {
    const [tipo, setTipo] = useState('all');
    const [estado, setEstado] = useState('all');
    const [periodo, setPeriodo] = useState('all');
    const [desde, setDesde] = useState('');
    const [hasta, setHasta] = useState('');

    const items = [
      {
        id: 'tipo',
        label: 'Tipo',
        value: tipo,
        onChange: setTipo,
        options: [
          { value: 'all', label: 'Todos' },
          { value: 'recibos', label: 'Recibos' },
          { value: 'contratos', label: 'Contratos' },
          { value: 'certificados', label: 'Certificados' },
          { value: 'otros', label: 'Otros' },
        ],
      },
      {
        id: 'estado',
        label: 'Estado',
        value: estado,
        onChange: setEstado,
        options: [
          { value: 'all', label: 'Todos' },
          { value: 'vigente', label: 'Vigente' },
          { value: 'pendiente', label: 'Pendiente' },
          { value: 'archivado', label: 'Archivado' },
        ],
      },
      {
        id: 'periodo',
        label: 'Periodo',
        value: periodo,
        onChange: setPeriodo,
        options: [
          { value: 'all', label: 'Todos' },
          { value: '30d', label: 'Ultimos 30 dias' },
          { value: '60d', label: 'Ultimos 60 dias' },
          { value: '90d', label: 'Ultimos 90 dias' },
        ],
      },
    ];

    return (
      <Tabla
        {...args}
        filtersArea={
          <Filtros
            items={items}
            filterByLabel="Filtrar por:"
            importationLabel="Importacion"
            dateFromPlaceholder="Desde"
            dateToPlaceholder="Hasta"
            dateFromValue={desde}
            dateToValue={hasta}
            onDateFromChange={setDesde}
            onDateToChange={setHasta}
            mobileBreakpoint={1024}
          />
        }
      />
    );
  },
};
