/**
 * Modelo de filtros avanzados + chips (misma semántica que la historia Tabla «FiltrosAplicados»).
 * `buildDocumentosAppliedFiltersFromPayload` acepta configuración para el consumidor (campos, operadores, etiquetas).
 */

export const PERSONA_DOCS_FILTROS_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' },
];

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

export const PERSONA_DOCS_FILTROS_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' },
];

export const PERSONA_DOCS_OPERATORS_BY_FIELD = {
  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' },
  ],
};

/** Config por defecto del DS (chips coherentes con `PERSONA_DOCS_FILTROS_*`). */
export const DEFAULT_DOCUMENTOS_FILTROS_BUILD_CONFIG = {
  fields: PERSONA_DOCS_FILTROS_FIELDS,
  operatorsByField: PERSONA_DOCS_OPERATORS_BY_FIELD,
  fieldLabels: {},
  operatorLabels: {},
};

function 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 ?? '',
  };
}

function 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;
}

/**
 * @param {object} filtrosBuildConfig
 * @param {Array<{ value: string, label: string }>} filtrosBuildConfig.fields
 * @param {Record<string, Array<{ value: string, label: string }>>} filtrosBuildConfig.operatorsByField
 * @param {Record<string, string>} [filtrosBuildConfig.fieldLabels] — clave = `field` de la condición
 * @param {Record<string, string>} [filtrosBuildConfig.operatorLabels] — clave = `operator` de la condición
 */
function formatConditionLabel(condition, filtrosBuildConfig) {
  const {
    fields = [],
    operatorsByField = {},
    fieldLabels = {},
    operatorLabels = {},
  } = filtrosBuildConfig || DEFAULT_DOCUMENTOS_FILTROS_BUILD_CONFIG;

  const fieldId = condition?.field;
  const opId = condition?.operator;

  const fieldLabel =
    (fieldLabels && fieldLabels[fieldId]) ||
    (Array.isArray(fields) ? fields.find((f) => f && f.value === fieldId)?.label : null) ||
    fieldId;

  const opList = operatorsByField[fieldId];
  const operatorLabel =
    (operatorLabels && operatorLabels[opId]) ||
    (Array.isArray(opList) ? opList.find((o) => o && o.value === opId)?.label : null) ||
    opId;

  if (condition?.value && typeof condition.value === 'object') {
    const rangeValue = getConditionRangeValue(condition);
    const separator = rangeValue.from && rangeValue.to ? ' - ' : '';
    return `${fieldLabel} ${operatorLabel} ${rangeValue.from}${separator}${rangeValue.to}`.trim();
  }
  if (condition?.valueFrom !== undefined || condition?.valueTo !== undefined) {
    const rangeValue = getConditionRangeValue(condition);
    const separator = rangeValue.from && rangeValue.to ? ' - ' : '';
    return `${fieldLabel} ${operatorLabel} ${rangeValue.from}${separator}${rangeValue.to}`.trim();
  }
  return `${fieldLabel} ${operatorLabel} ${condition.value}`;
}

/**
 * @param {{ conditions?: unknown[], aiValue?: string }} payload
 * @param {typeof DEFAULT_DOCUMENTOS_FILTROS_BUILD_CONFIG} [filtrosBuildConfig]
 * @returns {Array<{ id: string, type: string, conditionId?: string, label: string }>}
 */
export function buildDocumentosAppliedFiltersFromPayload(payload, filtrosBuildConfig) {
  const cfg = filtrosBuildConfig ?? DEFAULT_DOCUMENTOS_FILTROS_BUILD_CONFIG;
  const conditionFilters = Array.isArray(payload?.conditions)
    ? payload.conditions
        .filter((condition) => conditionHasValue(condition))
        .map((condition) => ({
          id: `condition-${condition.id}`,
          type: 'condition',
          conditionId: condition.id,
          label: formatConditionLabel(condition, cfg),
        }))
    : [];
  const aiFilter = String(payload?.aiValue ?? '').trim();
  return aiFilter
    ? [{ id: 'ai-filter', type: 'ai', label: `BEE Asist ${aiFilter}` }, ...conditionFilters]
    : conditionFilters;
}

/** @deprecated Usar `buildDocumentosAppliedFiltersFromPayload(payload, DEFAULT_DOCUMENTOS_FILTROS_BUILD_CONFIG)`. */
export function buildPersonaDocumentosAppliedFiltersFromPayload(payload) {
  return buildDocumentosAppliedFiltersFromPayload(payload, DEFAULT_DOCUMENTOS_FILTROS_BUILD_CONFIG);
}
