import { useState, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Tabla, DEFAULT_TABLA_COLUMNS, DEFAULT_TABLA_ROWS } from '../Tabla/Tabla';
import {
  PERSONA_DOCS_FILTROS_INITIAL_CONDITIONS,
  PERSONA_DOCS_FILTROS_EMPTY_CONDITION,
  PERSONA_DOCS_FILTROS_FIELDS,
  PERSONA_DOCS_OPERATORS_BY_FIELD,
  buildDocumentosAppliedFiltersFromPayload,
} from './personaDocumentosTablaFiltrosModel.js';

function cloneConditions(list) {
  if (!Array.isArray(list)) return [];
  try {
    return structuredClone(list);
  } catch {
    return JSON.parse(JSON.stringify(list));
  }
}

/**
 * Panel pestaña Documentos: `Tabla` + filtros avanzados + chips.
 * Props opcionales permiten al consumidor definir columnas, filas, campos de filtro y props extra de `Tabla`.
 *
 * @param {object[]} [tableUsers]
 * @param {object[]} [tableColumns]
 * @param {object[]} [filtrosFields]
 * @param {Record<string, object[]>} [filtrosOperatorsByField]
 * @param {object[]} [filtrosInitialConditions]
 * @param {object} [filtrosEmptyCondition]
 * @param {Record<string, string>} [filtrosFieldLabels]
 * @param {Record<string, string>} [filtrosOperatorLabels]
 * @param {string} [searchPlaceholder]
 * @param {string} [filtersButtonLabel]
 * @param {boolean} [tableLoading]
 * @param {boolean} [sinContenido]
 * @param {string} [emptyStateLabel]
 * @param {object} [tablaExtraProps] — se fusionan al final sobre `Tabla` (p. ej. `toolbarIcons`, `registrosCurrent`, `onRegistrosPorPaginaCommit`).
 */
export function PersonaDocumentosTablaPanel({
  tableUsers,
  tableColumns,
  filtrosFields,
  filtrosOperatorsByField,
  filtrosInitialConditions,
  filtrosEmptyCondition,
  filtrosFieldLabels,
  filtrosOperatorLabels,
  searchPlaceholder: searchPlaceholderProp,
  filtersButtonLabel: filtersButtonLabelProp,
  tableLoading = false,
  sinContenido = false,
  emptyStateLabel,
  tablaExtraProps,
}) {
  const { t } = useTranslation();

  const resolvedUsers = tableUsers ?? DEFAULT_TABLA_ROWS;
  const resolvedColumns = tableColumns ?? DEFAULT_TABLA_COLUMNS;
  const resolvedFields = filtrosFields ?? PERSONA_DOCS_FILTROS_FIELDS;
  const resolvedOperatorsByField = filtrosOperatorsByField ?? PERSONA_DOCS_OPERATORS_BY_FIELD;
  const resolvedInitialConditions = filtrosInitialConditions ?? PERSONA_DOCS_FILTROS_INITIAL_CONDITIONS;
  const resolvedEmptyCondition = filtrosEmptyCondition ?? PERSONA_DOCS_FILTROS_EMPTY_CONDITION;

  const filtrosBuildConfig = useMemo(
    () => ({
      fields: resolvedFields,
      operatorsByField: resolvedOperatorsByField,
      fieldLabels: filtrosFieldLabels ?? {},
      operatorLabels: filtrosOperatorLabels ?? {},
    }),
    [resolvedFields, resolvedOperatorsByField, filtrosFieldLabels, filtrosOperatorLabels],
  );

  const buildApplied = useCallback(
    (payload) => buildDocumentosAppliedFiltersFromPayload(payload, filtrosBuildConfig),
    [filtrosBuildConfig],
  );

  const [searchValue, setSearchValue] = useState('');
  const [conditions, setConditions] = useState(() => cloneConditions(resolvedInitialConditions));
  const [aiValue, setAiValue] = useState('');
  const [appliedFilters, setAppliedFilters] = useState(() =>
    buildDocumentosAppliedFiltersFromPayload(
      { conditions: cloneConditions(resolvedInitialConditions), aiValue: '' },
      {
        fields: resolvedFields,
        operatorsByField: resolvedOperatorsByField,
        fieldLabels: filtrosFieldLabels ?? {},
        operatorLabels: filtrosOperatorLabels ?? {},
      },
    ),
  );
  const [currentPage, setCurrentPage] = useState(1);
  const totalPages = 1;

  const clearFilters = useCallback(() => {
    setConditions([{ ...resolvedEmptyCondition }]);
    setAiValue('');
    setAppliedFilters([]);
  }, [resolvedEmptyCondition]);

  const syncAppliedFilters = useCallback(
    (nextConditions, nextAiValue) => {
      setAppliedFilters(buildApplied({ conditions: nextConditions, aiValue: nextAiValue }));
    },
    [buildApplied],
  );

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

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

  const removeAppliedFilter = useCallback(
    (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));
    },
    [],
  );

  const searchPlaceholderResolved =
    searchPlaceholderProp ??
    t('persona.alta.documentosSearchPlaceholder', {
      defaultValue: "Buscar dentro de 'Documentos'",
    });

  const filtersButtonLabelResolved = filtersButtonLabelProp ?? t('table.filters', { defaultValue: 'Filtros' });

  const extra = tablaExtraProps && typeof tablaExtraProps === 'object' ? tablaExtraProps : {};

  return (
    <Tabla
      users={resolvedUsers}
      tableColumns={resolvedColumns}
      tableLoading={tableLoading}
      sinContenido={sinContenido}
      emptyStateLabel={emptyStateLabel}
      searchPlaceholder={searchPlaceholderResolved}
      searchValue={searchValue}
      onSearchChange={(value) => setSearchValue(value)}
      showFiltersButton
      filtersButtonLabel={filtersButtonLabelResolved}
      currentPage={currentPage}
      totalPages={totalPages}
      onPrevPage={() => setCurrentPage((p) => Math.max(1, p - 1))}
      onNextPage={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
      filtersAreaContainerStyle={{
        marginTop: '16px',
        marginBottom: '16px',
      }}
      activeFiltersCount={appliedFilters.length}
      appliedFilters={appliedFilters}
      onAppliedFilterRemove={removeAppliedFilter}
      onAppliedFiltersClear={clearFilters}
      onAdvancedFiltersApply={(payload) => {
        setConditions(payload.conditions ?? [{ ...resolvedEmptyCondition }]);
        setAiValue(payload.aiValue ?? '');
        setAppliedFilters(buildApplied(payload));
      }}
      advancedFiltersModalProps={{
        fields: resolvedFields,
        operatorsByField: resolvedOperatorsByField,
        conditions,
        aiValue,
        onConditionsChange: handleConditionsChange,
        onAiChange: handleAiChange,
        onClear: clearFilters,
      }}
      containerStyle={{ minHeight: 0 }}
      {...extra}
    />
  );
}
