import { useEffect, useMemo, useRef, useState } from 'react';
import { Icon } from '../../Atoms/Icon/Icon';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { PrimaryInput } from '../../Inputs/PrimaryInput/PrimaryInput';
import { Calendario } from '../../Inputs/Calendario/Calendario';
import { FONT_FAMILY_SANS } from '../../../designTokens';

const DEFAULT_FIELDS = [
  { value: 'documento', label: 'Documento' },
  { value: 'persona', label: 'Persona' },
  { value: 'fechaImportacion', label: 'Fecha de import...' },
];

const DEFAULT_OPERATORS = [
  { value: 'contiene', label: 'contiene' },
  { value: 'noContiene', label: 'no contiene' },
  { value: 'antesDe', label: 'antes de' },
  { value: 'despuesDe', label: 'después de' },
  { value: 'igualA', label: 'igual a' },
];

const DEFAULT_CONDITIONS = [
  { id: 'documento-contiene', field: 'documento', operator: 'contiene', value: '' },
  { id: 'persona-no-contiene', field: 'persona', operator: 'noContiene', value: '' },
  { id: 'fecha-antes-de', field: 'fechaImportacion', operator: 'antesDe', value: '' },
];

const textBaseStyle = {
  fontFamily: FONT_FAMILY_SANS,
  color: '#29474C',
};

const selectStyle = {
  ...textBaseStyle,
  width: '190px',
  height: '44px',
  border: '1px solid #38656D',
  borderRadius: '8px',
  background: '#FFFFFF',
  padding: '10px 40px 10px 12px',
  fontSize: '16px',
  lineHeight: '24px',
  fontWeight: 400,
  outline: 'none',
  appearance: 'none',
  WebkitAppearance: 'none',
  MozAppearance: 'none',
  boxSizing: 'border-box',
  cursor: 'pointer',
};

const inputStyle = {
  ...textBaseStyle,
  width: '190px',
  height: '44px',
  border: '1px solid #38656D',
  borderRadius: '8px',
  background: '#FFFFFF',
  padding: '10px 12px',
  fontSize: '16px',
  lineHeight: '24px',
  fontWeight: 400,
  outline: 'none',
  boxSizing: 'border-box',
};

const buttonTextStyle = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 500,
  fontSize: '14px',
  lineHeight: '21px',
  letterSpacing: '0.01em',
};

const formatDateDisplay = (isoValue) => {
  if (!isoValue || !/^\d{4}-\d{2}-\d{2}$/.test(isoValue)) return isoValue || '';
  const [year, month, day] = isoValue.split('-');
  return `${day}-${month}-${year}`;
};

const formatPeriodDisplay = (periodValue) => {
  if (!periodValue || !/^\d{4}-\d{2}$/.test(periodValue)) return periodValue || '';
  const [year, month] = periodValue.split('-');
  return `${month}-${year}`;
};

const isBetweenOperator = (operatorValue) => {
  if (!operatorValue) return false;
  const normalizedOperator = String(operatorValue).toLowerCase();
  return normalizedOperator === 'between' || normalizedOperator === 'entre';
};

const getRangeValue = (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 normalizeConditionValue = (condition, { isBetween }) => {
  if (isBetween) return getRangeValue(condition);
  if (condition?.value && typeof condition.value === 'object') {
    const rangeValue = getRangeValue(condition);
    return rangeValue.from || rangeValue.to || '';
  }
  return condition?.value ?? '';
};

const getOperatorsForField = (fieldValue, operators, operatorsByField) => {
  const fieldOperators = operatorsByField?.[fieldValue];
  return Array.isArray(fieldOperators) && fieldOperators.length > 0 ? fieldOperators : operators;
};

const getPreferredOperator = (operatorsList) => {
  if (!Array.isArray(operatorsList) || operatorsList.length === 0) return '';
  const singleValueOperator = operatorsList.find((item) => !isBetweenOperator(item?.value));
  return (singleValueOperator ?? operatorsList[0])?.value ?? '';
};

const getFieldTemporalType = (field, fieldValue) => {
  if (isListField(field)) return null;
  const explicitType = field?.type;
  if (explicitType === 'period' || explicitType === 'month') return 'month';
  if (explicitType === 'date' || String(fieldValue ?? '').toLowerCase().includes('fecha')) return 'date';
  return null;
};

const isListField = (field) => {
  const explicitType = field?.type;
  return explicitType === 'list' || explicitType === 'select';
};

const getListOptionsForField = (field) =>
  Array.isArray(field?.options) ? field.options : [];

function SelectField({
  value,
  options,
  onChange,
  ariaLabel,
  id,
  name,
  dataField,
  placeholder,
  containerWidth = '190px',
}) {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef(null);
  const selectedOption = options.find((option) => option.value === value);

  useEffect(() => {
    if (!isOpen) return undefined;
    const handleClickOutside = (event) => {
      if (containerRef.current && !containerRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isOpen]);

  const displayLabel = selectedOption?.label ?? (value ? '' : placeholder) ?? '';

  return (
    <div ref={containerRef} style={{ position: 'relative', width: containerWidth }}>
      <button
        type="button"
        id={id}
        name={name}
        data-filter-field={dataField}
        aria-label={ariaLabel}
        onClick={() => setIsOpen((prev) => !prev)}
        style={{
          ...selectStyle,
          width: '100%',
          color: selectedOption ? selectStyle.color : '#777777',
          fontStyle: selectedOption ? 'normal' : 'italic',
        }}
      >
        <span
          style={{
            display: 'block',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            textAlign: 'left',
          }}
        >
          {displayLabel}
        </span>
      </button>
      <Icon
        name="ChevronDownIcon"
        variant="24-outline"
        size={18}
        style={{
          position: 'absolute',
          right: '12px',
          top: '50%',
          transform: 'translateY(-50%)',
          pointerEvents: 'none',
          color: '#38656D',
        }}
      />
      {isOpen && (
        <div
          className="anima-filtros-avanzados-select-menu"
          style={{
            position: 'absolute',
            top: 'calc(100% + 4px)',
            left: 0,
            zIndex: 80,
            width: '189px',
            height: 'auto',
            maxHeight: '296px',
            opacity: 1,
            borderRadius: '12px',
            border: '1px solid #38656D',
            borderTop: '1px solid #38656D',
            padding: '8px',
            background: '#FFFFFF',
            boxSizing: 'border-box',
            overflowY: 'auto',
            scrollbarWidth: 'none',
            msOverflowStyle: 'none',
          }}
        >
          {options.map((option) => {
            const isSelected = option.value === value;
            return (
              <button
                key={option.value}
                type="button"
                className="anima-filtros-avanzados-select-item"
                onClick={() => {
                  onChange?.(option.value);
                  setIsOpen(false);
                }}
                style={{
                  width: '173px',
                  height: '40px',
                  opacity: 1,
                  borderRadius: '8px',
                  gap: '16px',
                  padding: '8px',
                  border: 'none',
                  background: isSelected ? '#6D3856' : '#FFFFFF',
                  color: isSelected ? '#FFFFFF' : '#29474C',
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 450,
                  fontStyle: 'normal',
                  fontSize: '16px',
                  lineHeight: '24px',
                  letterSpacing: '0px',
                  textAlign: 'left',
                  cursor: 'pointer',
                  boxSizing: 'border-box',
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                {option.label}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function useIsMobile(breakpoint) {
  const [isMobile, setIsMobile] = useState(() =>
    typeof window !== 'undefined' ? window.matchMedia(`(max-width: ${breakpoint}px)`).matches : false
  );

  useEffect(() => {
    if (typeof window === 'undefined') return undefined;
    const mql = window.matchMedia(`(max-width: ${breakpoint}px)`);
    const handle = () => setIsMobile(mql.matches);
    handle();
    mql.addEventListener('change', handle);
    return () => mql.removeEventListener('change', handle);
  }, [breakpoint]);

  return isMobile;
}

function ConditionValueField({
  condition,
  conditionIndex,
  isTemporal,
  calendarMode = 'date',
  value,
  placeholder,
  ariaLabel,
  fieldKeySuffix = 'value',
  containerWidth = '190px',
  inputLabel,
  onTextChange,
  onDateChange,
  onDateClear,
}) {
  const containerRef = useRef(null);
  const [isCalendarOpen, setIsCalendarOpen] = useState(false);
  const [calendarPlacement, setCalendarPlacement] = useState({ openUp: false, alignRight: true });
  const CALENDAR_WIDTH = 320;
  const CALENDAR_HEIGHT = 360;

  const openCalendar = () => {
    if (!isTemporal) return;
    setIsCalendarOpen(true);
  };

  useEffect(() => {
    if (!isCalendarOpen) return undefined;
    const handleClickOutside = (event) => {
      if (containerRef.current && !containerRef.current.contains(event.target)) {
        setIsCalendarOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isCalendarOpen]);

  useEffect(() => {
    if (!isCalendarOpen || typeof window === 'undefined') return;
    const el = containerRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const spaceRight = window.innerWidth - rect.left;
    const spaceBottom = window.innerHeight - rect.bottom;
    setCalendarPlacement({
      alignRight: spaceRight < CALENDAR_WIDTH && rect.right > CALENDAR_WIDTH,
      openUp: spaceBottom < CALENDAR_HEIGHT && rect.top > CALENDAR_HEIGHT,
    });
  }, [isCalendarOpen]);

  return (
    <div ref={containerRef} style={{ position: 'relative', width: containerWidth }}>
      {inputLabel ? (
        <span
          style={{
            ...textBaseStyle,
            display: 'block',
            marginBottom: '6px',
            fontWeight: 500,
            fontSize: '12px',
            lineHeight: '18px',
          }}
        >
          {inputLabel}
        </span>
      ) : null}
      <PrimaryInput
        type="text"
        id={`advanced-filter-condition-${conditionIndex + 1}-${fieldKeySuffix}`}
        name={`advancedFilterCondition${conditionIndex + 1}${fieldKeySuffix}`}
        aria-label={ariaLabel}
        data-filter-field={`condition-${conditionIndex + 1}-${fieldKeySuffix}`}
        value={isTemporal ? (calendarMode === 'month' ? formatPeriodDisplay(value) : formatDateDisplay(value)) : (value ?? '')}
        placeholder={placeholder}
        readOnly={isTemporal}
        onClick={isTemporal ? openCalendar : undefined}
        onChange={(event) => {
          if (isTemporal) return;
          onTextChange?.(event.target.value);
        }}
        className="anima-filtros-avanzados-input"
        style={{
          ...inputStyle,
          paddingRight: isTemporal ? '40px' : '12px',
          fontStyle: value ? 'normal' : 'italic',
          color: value ? '#29474C' : '#777777',
        }}
      />
      {isTemporal && (
        <button
          type="button"
          onMouseDown={(event) => event.preventDefault()}
          onClick={openCalendar}
          aria-label={`Abrir calendario de condición ${conditionIndex + 1} - ${fieldKeySuffix}`}
          data-filter-field={`condition-${conditionIndex + 1}-${fieldKeySuffix}-calendar`}
          style={{
            position: 'absolute',
            right: '12px',
            top: '50%',
            transform: 'translateY(-50%)',
            border: 'none',
            background: 'transparent',
            padding: 0,
            color: '#38656D',
            cursor: 'pointer',
          }}
        >
          <Icon name="CalendarDaysIcon" variant="24-outline" size={16} />
        </button>
      )}
      {isTemporal && isCalendarOpen && (
        <div
          style={{
            position: 'absolute',
            zIndex: 90,
            top: calendarPlacement.openUp ? 'auto' : 'calc(100% + 8px)',
            bottom: calendarPlacement.openUp ? 'calc(100% + 8px)' : 'auto',
            left: calendarPlacement.alignRight ? 'auto' : 0,
            right: calendarPlacement.alignRight ? 0 : 'auto',
          }}
        >
          <Calendario
            value={value}
            mode={calendarMode}
            onChange={(nextValue) => onDateChange?.(nextValue)}
            onClear={() => onDateClear?.()}
            onClose={() => setIsCalendarOpen(false)}
          />
        </div>
      )}
    </div>
  );
}

export const FiltrosAvanzados = ({
  isOpen = false,
  onClose,
  title = 'Filtros avanzados',
  beeAssistantLabel = 'BEE Asist - Filtrado con IA',
  beeAssistantPlaceholder = 'Ej: Filtrar por los documentos de empleados ubicados en Tucuman',
  aiValue,
  onAiChange,
  conditions,
  defaultConditions = DEFAULT_CONDITIONS,
  onConditionsChange,
  fields = DEFAULT_FIELDS,
  operators = DEFAULT_OPERATORS,
  operatorsByField,
  conditionsLabel = 'Condiciones',
  addConditionLabel = 'Añadir condición',
  clearLabel = 'Limpiar filtros',
  applyLabel = 'Filtrar',
  cancelLabel = 'Cancelar',
  children,
  footer,
  size,
  onApply,
  onCancel,
  onClear,
  mobileBreakpoint = 768,
  closeOnOverlayClick = true,
  className = '',
  style,
  ...props
}) => {
  const isMobile = useIsMobile(mobileBreakpoint);
  const isConditionsControlled = Array.isArray(conditions);
  const [internalConditions, setInternalConditions] = useState(defaultConditions);
  const [internalAiValue, setInternalAiValue] = useState('');
  const currentConditions = isConditionsControlled ? conditions : internalConditions;
  const currentAiValue = aiValue !== undefined ? aiValue : internalAiValue;

  const fieldMap = useMemo(
    () => new Map(fields.map((field) => [field.value, field])),
    [fields],
  );

  useEffect(() => {
    if (!isOpen || typeof document === 'undefined') return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [isOpen]);

  if (!isOpen) return null;

  const setNextConditions = (nextConditions) => {
    if (!isConditionsControlled) setInternalConditions(nextConditions);
    onConditionsChange?.(nextConditions);
  };

  const updateCondition = (conditionId, key, value) => {
    setNextConditions(
      currentConditions.map((condition) =>
        condition.id === conditionId ? { ...condition, [key]: value } : condition
      )
    );
  };

  const removeCondition = (conditionId) => {
    setNextConditions(currentConditions.filter((condition) => condition.id !== conditionId));
  };

  const addCondition = () => {
    const firstField = fields[0]?.value ?? '';
    const availableOperators = getOperatorsForField(firstField, operators, operatorsByField);
    setNextConditions([
      ...currentConditions,
      {
        id: `condition-${Date.now()}`,
        field: firstField,
        operator: getPreferredOperator(availableOperators),
        value: '',
      },
    ]);
  };

  const clearFilters = () => {
    if (!isConditionsControlled) {
      const firstField = fields[0]?.value ?? '';
      const firstOperator = getPreferredOperator(getOperatorsForField(firstField, operators, operatorsByField));
      setInternalConditions([{ id: 'condition-first', field: firstField, operator: firstOperator, value: '' }]);
    }
    if (aiValue === undefined) setInternalAiValue('');
    onClear?.();
  };

  const renderConditionValueInput = (condition, index) => {
    const field = fieldMap.get(condition.field);
    const isList = isListField(field);
    const listOptions = isList ? getListOptionsForField(field) : [];
    const temporalType = getFieldTemporalType(field, condition.field);
    const isTemporal = temporalType !== null;
    const calendarMode = temporalType === 'month' ? 'month' : 'date';
    const isBetween = isBetweenOperator(condition.operator);

    if (isList && isBetween) {
      const rangeValue = getRangeValue(condition);
      return (
        <div
          className="anima-filtros-avanzados-range-value"
          style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}
        >
          <div>
            <span
              style={{
                ...textBaseStyle,
                display: 'block',
                marginBottom: '6px',
                fontWeight: 500,
                fontSize: '12px',
                lineHeight: '18px',
              }}
            >
              Desde
            </span>
            <SelectField
              id={`advanced-filter-condition-${index + 1}-value-from`}
              name={`advancedFilterCondition${index + 1}ValueFrom`}
              dataField={`condition-${index + 1}-value-from`}
              ariaLabel={`Desde de condición ${index + 1}`}
              value={rangeValue.from}
              options={listOptions}
              placeholder={field?.placeholder ?? 'Seleccionar...'}
              onChange={(nextValue) =>
                updateCondition(condition.id, 'value', { ...rangeValue, from: nextValue ?? '' })
              }
            />
          </div>
          <div>
            <span
              style={{
                ...textBaseStyle,
                display: 'block',
                marginBottom: '6px',
                fontWeight: 500,
                fontSize: '12px',
                lineHeight: '18px',
              }}
            >
              Hasta
            </span>
            <SelectField
              id={`advanced-filter-condition-${index + 1}-value-to`}
              name={`advancedFilterCondition${index + 1}ValueTo`}
              dataField={`condition-${index + 1}-value-to`}
              ariaLabel={`Hasta de condición ${index + 1}`}
              value={rangeValue.to}
              options={listOptions}
              placeholder={field?.placeholder ?? 'Seleccionar...'}
              onChange={(nextValue) =>
                updateCondition(condition.id, 'value', { ...rangeValue, to: nextValue ?? '' })
              }
            />
          </div>
        </div>
      );
    }

    if (isList) {
      return (
        <SelectField
          id={`advanced-filter-condition-${index + 1}-value`}
          name={`advancedFilterCondition${index + 1}Value`}
          dataField={`condition-${index + 1}-value`}
          ariaLabel={`Valor de condición ${index + 1}`}
          value={condition.value ?? ''}
          options={listOptions}
          placeholder={field?.placeholder ?? 'Seleccionar...'}
          onChange={(nextValue) => updateCondition(condition.id, 'value', nextValue)}
        />
      );
    }

    if (isTemporal && isBetween) {
      const rangeValue = getRangeValue(condition);
      return (
        <div
          className="anima-filtros-avanzados-range-value"
          style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}
        >
          <ConditionValueField
            condition={condition}
            conditionIndex={index}
            isTemporal
            calendarMode={calendarMode}
            value={rangeValue.from}
            inputLabel="Desde"
            fieldKeySuffix="value-from"
            placeholder={calendarMode === 'month' ? 'MM-YYYY' : 'DD-MM-YYYY'}
            ariaLabel={`Desde de condición ${index + 1}`}
            onDateChange={(nextValue) =>
              updateCondition(condition.id, 'value', { ...rangeValue, from: nextValue ?? '' })
            }
            onDateClear={() => updateCondition(condition.id, 'value', { ...rangeValue, from: '' })}
          />
          <ConditionValueField
            condition={condition}
            conditionIndex={index}
            isTemporal
            calendarMode={calendarMode}
            value={rangeValue.to}
            inputLabel="Hasta"
            fieldKeySuffix="value-to"
            placeholder={calendarMode === 'month' ? 'MM-YYYY' : 'DD-MM-YYYY'}
            ariaLabel={`Hasta de condición ${index + 1}`}
            onDateChange={(nextValue) =>
              updateCondition(condition.id, 'value', { ...rangeValue, to: nextValue ?? '' })
            }
            onDateClear={() => updateCondition(condition.id, 'value', { ...rangeValue, to: '' })}
          />
        </div>
      );
    }

    return (
      <ConditionValueField
        condition={condition}
        conditionIndex={index}
        isTemporal={isTemporal}
        calendarMode={calendarMode}
        value={condition.value}
        placeholder={
          isTemporal
            ? (calendarMode === 'month' ? 'MM-YYYY' : 'DD-MM-YYYY')
            : condition.field === 'persona'
              ? 'Ej: Laura Gómez'
              : 'Filtrar por documento'
        }
        ariaLabel={`Valor de condición ${index + 1}`}
        onTextChange={(nextValue) => updateCondition(condition.id, 'value', nextValue)}
        onDateChange={(nextValue) => updateCondition(condition.id, 'value', nextValue)}
        onDateClear={() => updateCondition(condition.id, 'value', '')}
      />
    );
  };

  const renderConditionRow = (condition, index) => {
    const canDelete = index !== 0;
    const conditionOperators = getOperatorsForField(condition.field, operators, operatorsByField);
    if (isMobile) {
      return (
        <div
          key={condition.id}
          style={{
            display: 'flex',
            flexDirection: 'column',
            gap: '10px',
            paddingTop: index === 0 ? 0 : '14px',
            borderTop: index === 0 ? 'none' : '1px solid #DDDDDD',
          }}
        >
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
            <div className="anima-filtros-avanzados-mobile-field">
              <SelectField
                id={`advanced-filter-condition-${index + 1}-field`}
                name={`advancedFilterCondition${index + 1}Field`}
                dataField={`condition-${index + 1}-field`}
                ariaLabel={`Campo de condición ${index + 1}`}
                value={condition.field}
                options={fields}
                onChange={(value) => {
                  const nextField = fields.find((item) => item.value === value);
                  const nextIsList = isListField(nextField);
                  const nextIsTemporal = !nextIsList && getFieldTemporalType(nextField, value) !== null;
                  const nextOperators = getOperatorsForField(value, operators, operatorsByField);
                  const currentOperatorExists = nextOperators.some((item) => item.value === condition.operator);
                  const nextOperator = currentOperatorExists ? condition.operator : getPreferredOperator(nextOperators);
                  setNextConditions(
                    currentConditions.map((currentCondition) =>
                      currentCondition.id === condition.id
                        ? {
                            ...currentCondition,
                            field: value,
                            operator: nextOperator,
                            value: nextIsList
                              ? ''
                              : normalizeConditionValue(currentCondition, {
                                  isBetween: isBetweenOperator(nextOperator),
                                }),
                          }
                        : currentCondition
                    )
                  );
                }}
              />
            </div>
            <div className="anima-filtros-avanzados-mobile-field">
              <SelectField
                id={`advanced-filter-condition-${index + 1}-operator`}
                name={`advancedFilterCondition${index + 1}Operator`}
                dataField={`condition-${index + 1}-operator`}
                ariaLabel={`Operador de condición ${index + 1}`}
                value={condition.operator}
                options={conditionOperators}
                onChange={(value) => {
                  setNextConditions(
                    currentConditions.map((currentCondition) => {
                      if (currentCondition.id !== condition.id) return currentCondition;
                      const currentField = fieldMap.get(currentCondition.field);
                      const currentIsList = isListField(currentField);
                      const currentIsTemporal =
                        !currentIsList && getFieldTemporalType(currentField, currentCondition.field) !== null;
                      return {
                        ...currentCondition,
                        operator: value,
                        value: currentIsList
                          ? normalizeConditionValue(currentCondition, {
                              isBetween: isBetweenOperator(value),
                            })
                          : normalizeConditionValue(currentCondition, {
                              isBetween: isBetweenOperator(value),
                            }),
                      };
                    })
                  );
                }}
              />
            </div>
          </div>
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: canDelete ? '1fr 44px' : '1fr',
              gap: '14px',
              alignItems: 'center',
            }}
          >
            <div className="anima-filtros-avanzados-mobile-value">
              {renderConditionValueInput(condition, index)}
            </div>
            {canDelete && (
              <button
                type="button"
                id={`advanced-filter-condition-${index + 1}-remove`}
                name={`advancedFilterCondition${index + 1}Remove`}
                data-filter-field={`condition-${index + 1}-remove`}
                onClick={() => removeCondition(condition.id)}
                aria-label={`Eliminar condición ${index + 1}`}
                style={{
                  width: '44px',
                  height: '44px',
                  minWidth: '44px',
                  justifySelf: 'end',
                  border: '1px solid #38656D',
                  borderRadius: '8px',
                  background: '#FFFFFF',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#38656D',
                  cursor: 'pointer',
                  boxSizing: 'border-box',
                }}
              >
                <Icon name="TrashIcon" variant="24-outline" size={20} />
              </button>
            )}
          </div>
        </div>
      );
    }

    return (
      <div
        key={condition.id}
        style={{
          display: 'grid',
          gridTemplateColumns: '190px 190px 190px 44px',
          columnGap: '12px',
          alignItems: 'center',
        }}
      >
        <SelectField
          id={`advanced-filter-condition-${index + 1}-field`}
          name={`advancedFilterCondition${index + 1}Field`}
          dataField={`condition-${index + 1}-field`}
          ariaLabel={`Campo de condición ${index + 1}`}
          value={condition.field}
          options={fields}
          onChange={(value) => {
            const nextField = fields.find((item) => item.value === value);
            const nextIsList = isListField(nextField);
            const nextIsTemporal = !nextIsList && getFieldTemporalType(nextField, value) !== null;
            const nextOperators = getOperatorsForField(value, operators, operatorsByField);
            const currentOperatorExists = nextOperators.some((item) => item.value === condition.operator);
            const nextOperator = currentOperatorExists ? condition.operator : getPreferredOperator(nextOperators);
            setNextConditions(
              currentConditions.map((currentCondition) =>
                currentCondition.id === condition.id
                  ? {
                      ...currentCondition,
                      field: value,
                      operator: nextOperator,
                      value: nextIsList
                        ? ''
                        : normalizeConditionValue(currentCondition, {
                            isBetween: isBetweenOperator(nextOperator),
                          }),
                    }
                  : currentCondition
              )
            );
          }}
        />
        <SelectField
          id={`advanced-filter-condition-${index + 1}-operator`}
          name={`advancedFilterCondition${index + 1}Operator`}
          dataField={`condition-${index + 1}-operator`}
          ariaLabel={`Operador de condición ${index + 1}`}
          value={condition.operator}
          options={conditionOperators}
          onChange={(value) => {
            setNextConditions(
              currentConditions.map((currentCondition) => {
                if (currentCondition.id !== condition.id) return currentCondition;
                const currentField = fieldMap.get(currentCondition.field);
                const currentIsList = isListField(currentField);
                const currentIsTemporal =
                  !currentIsList && getFieldTemporalType(currentField, currentCondition.field) !== null;
                return {
                  ...currentCondition,
                  operator: value,
                  value: currentIsList
                    ? normalizeConditionValue(currentCondition, {
                        isBetween: isBetweenOperator(value),
                      })
                    : normalizeConditionValue(currentCondition, {
                        isBetween: isBetweenOperator(value),
                      }),
                };
              })
            );
          }}
        />
        {renderConditionValueInput(condition, index)}
        {canDelete ? (
          <button
            type="button"
            id={`advanced-filter-condition-${index + 1}-remove`}
            name={`advancedFilterCondition${index + 1}Remove`}
            data-filter-field={`condition-${index + 1}-remove`}
            onClick={() => removeCondition(condition.id)}
            aria-label={`Eliminar condición ${index + 1}`}
            style={{
              width: '44px',
              height: '44px',
              minWidth: '44px',
              border: '1px solid #38656D',
              borderRadius: '8px',
              background: '#FFFFFF',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: '#38656D',
              cursor: 'pointer',
              boxSizing: 'border-box',
            }}
          >
            <Icon name="TrashIcon" variant="24-outline" size={20} />
          </button>
        ) : (
          <div aria-hidden="true" style={{ width: '44px', height: '44px' }} />
        )}
      </div>
    );
  };

  return (
    <div
      className="anima-filtros-avanzados-overlay"
      style={{
        position: 'fixed',
        inset: 0,
        zIndex: 60,
        background: '#00000040',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        boxSizing: 'border-box',
      }}
      onClick={() => {
        if (closeOnOverlayClick) onClose?.();
      }}
      {...props}
    >
      <div
        className={className}
        style={{
          width: isMobile ? '100vw' : '684px',
          maxWidth: isMobile ? 'none' : '684px',
          minHeight: isMobile ? '100vh' : '512px',
          height: isMobile ? '100vh' : 'auto',
          maxHeight: isMobile ? '100vh' : 'calc(100vh - 48px)',
          opacity: 1,
          borderRadius: isMobile ? 0 : '16px',
          border: '1px solid #C4C4C4',
          background: '#FFFFFF',
          boxSizing: 'border-box',
          overflow: 'visible',
          display: 'flex',
          flexDirection: 'column',
          fontFamily: FONT_FAMILY_SANS,
          ...style,
        }}
        onClick={(event) => event.stopPropagation()}
      >
        <style>{`
          .anima-filtros-avanzados-input::placeholder {
            color: #777777;
            font-family: ${FONT_FAMILY_SANS};
            font-style: italic;
            opacity: 1;
          }
          .anima-filtros-avanzados-select-menu::-webkit-scrollbar {
            width: 0;
            height: 0;
            display: none;
          }
          .anima-filtros-avanzados-select-item:hover {
            background: #DDDDDD !important;
            color: #29474C !important;
          }
          @media (max-width: ${mobileBreakpoint}px) {
            .anima-filtros-avanzados-mobile-field > div,
            .anima-filtros-avanzados-mobile-field button,
            .anima-filtros-avanzados-mobile-value > div,
            .anima-filtros-avanzados-mobile-value .anima-filtros-avanzados-range-value > div,
            .anima-filtros-avanzados-mobile-value input {
              width: 100% !important;
            }
            .anima-filtros-avanzados-mobile-field .anima-filtros-avanzados-select-menu {
              width: 100% !important;
              min-width: 0 !important;
            }
            .anima-filtros-avanzados-mobile-field .anima-filtros-avanzados-select-item {
              width: 100% !important;
            }
          }
        `}</style>
        <div
          style={{
            height: isMobile ? '56px' : '72px',
            padding: isMobile ? '16px 12px 8px 12px' : '24px 18px 12px 18px',
            display: 'flex',
            alignItems: 'flex-start',
            justifyContent: 'space-between',
            boxSizing: 'border-box',
            flexShrink: 0,
          }}
        >
          <h2
            style={{
              ...textBaseStyle,
              margin: 0,
              fontWeight: 400,
              fontSize: isMobile ? '16px' : '20px',
              lineHeight: isMobile ? '24px' : '30px',
              letterSpacing: '0px',
            }}
          >
            {title}
          </h2>
          <button
            type="button"
            onClick={onClose}
            aria-label="Cerrar filtros avanzados"
            style={{
              border: 'none',
              background: 'transparent',
              padding: 0,
              width: '24px',
              height: '24px',
              cursor: 'pointer',
              color: '#29474C',
            }}
          >
            <Icon name="XMarkIcon" variant="24-outline" size={24} />
          </button>
        </div>

        <div
          style={{
            flex: 1,
            minHeight: 0,
            padding: isMobile ? '0 12px 16px 12px' : '0 18px',
            boxSizing: 'border-box',
            overflowY: isMobile ? 'auto' : 'visible',
            overflowX: 'visible',
          }}
        >
          {children ?? (
            <>
              <label
                style={{
                  ...textBaseStyle,
                  display: 'block',
                  marginBottom: isMobile ? '6px' : '8px',
                  fontWeight: 600,
                  fontSize: '14px',
                  lineHeight: '21px',
                }}
              >
                {beeAssistantLabel}
              </label>
              <div style={{ position: 'relative', width: '100%', marginBottom: isMobile ? '14px' : '22px' }}>
                <PrimaryInput
                  className="anima-filtros-avanzados-input"
                  type="text"
                  id="advanced-filter-ai-input"
                  name="advancedFilterAiInput"
                  aria-label={beeAssistantLabel}
                  data-filter-field="ai-input"
                  value={currentAiValue}
                  placeholder={beeAssistantPlaceholder}
                  onChange={(event) => {
                    if (aiValue === undefined) setInternalAiValue(event.target.value);
                    onAiChange?.(event.target.value);
                  }}
                  style={{
                    ...inputStyle,
                    width: '100%',
                    height: isMobile ? '72px' : '44px',
                    borderRadius: '8px',
                    borderWidth: '1px',
                    paddingTop: isMobile ? '12px' : '10px',
                    paddingRight: isMobile ? '16px' : '44px',
                    paddingBottom: isMobile ? '12px' : '10px',
                    paddingLeft: isMobile ? '16px' : '12px',
                    fontStyle: currentAiValue ? 'normal' : 'italic',
                    color: currentAiValue ? '#29474C' : '#777777',
                  }}
                />
                <Icon
                  name="SparklesIcon"
                  variant="24-outline"
                  size={20}
                  style={{
                    position: 'absolute',
                    right: isMobile ? '16px' : '12px',
                    top: '50%',
                    transform: 'translateY(-50%)',
                    color: '#38656D',
                    pointerEvents: 'none',
                  }}
                />
              </div>

              <span
                style={{
                  ...textBaseStyle,
                  display: 'block',
                  marginBottom: '10px',
                  fontWeight: 600,
                  fontSize: '14px',
                  lineHeight: '21px',
                }}
              >
                {conditionsLabel}
              </span>

              <div style={{ display: 'flex', flexDirection: 'column', gap: isMobile ? '14px' : '16px' }}>
                {currentConditions.map((condition, index) => renderConditionRow(condition, index))}
              </div>

              <PrimaryActionButton
                type="button"
                id="advanced-filter-add-condition"
                name="advancedFilterAddCondition"
                data-filter-field="add-condition"
                onClick={addCondition}
                variant="outline"
                style={{
                  marginTop: '20px',
                  marginLeft: 0,
                  minWidth: 'auto',
                  height: '40px',
                  width: isMobile ? '100%' : 'auto',
                  padding: '8px 12px',
                  border: '1px solid #38656D',
                  borderRadius: '8px',
                }}
                textStyle={{
                  ...buttonTextStyle,
                  color: '#38656D',
                }}
              >
                {addConditionLabel}
              </PrimaryActionButton>
              {isMobile && (
                <button
                  type="button"
                  id="advanced-filter-clear"
                  name="advancedFilterClear"
                  data-filter-field="clear-filters"
                  onClick={clearFilters}
                  style={{
                    width: '100%',
                    marginTop: '22px',
                    border: 'none',
                    background: 'transparent',
                    color: '#6D3856',
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 400,
                    fontSize: '14px',
                    lineHeight: '21px',
                    cursor: 'pointer',
                  }}
                >
                  {clearLabel}
                </button>
              )}
            </>
          )}
        </div>

        <div
          style={{
            height: isMobile ? '66px' : '80px',
            borderTop: '1px solid #DDDDDD',
            padding: isMobile ? '12px' : '20px 18px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: isMobile ? 'center' : 'space-between',
            boxSizing: 'border-box',
            flexShrink: 0,
          }}
        >
          {footer ?? (isMobile ? (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', width: '100%' }}>
              <PrimaryActionButton
                type="button"
                id="advanced-filter-cancel"
                name="advancedFilterCancel"
                data-filter-field="cancel"
                variant="outline"
                onClick={() => {
                  onCancel?.();
                  onClose?.();
                }}
                fullWidth
                style={{
                  marginLeft: 0,
                  minWidth: 0,
                  height: '44px',
                  padding: '8px 12px',
                  borderRadius: '8px',
                  border: '1px solid #38656D',
                }}
                textStyle={{
                  ...buttonTextStyle,
                  color: '#38656D',
                }}
              >
                {cancelLabel}
              </PrimaryActionButton>
              <PrimaryActionButton
                type="button"
                id="advanced-filter-apply"
                name="advancedFilterApply"
                data-filter-field="apply"
                variant="primary"
                onClick={() => {
                  onApply?.({ aiValue: currentAiValue, conditions: currentConditions });
                  onClose?.();
                }}
                fullWidth
                style={{
                  marginLeft: 0,
                  minWidth: 0,
                  height: '44px',
                  padding: '8px 12px',
                  borderRadius: '8px',
                  border: '1px solid #38656D',
                  background: '#38656D',
                }}
                textStyle={{
                  ...buttonTextStyle,
                  color: '#FFFFFF',
                }}
              >
                {applyLabel}
              </PrimaryActionButton>
            </div>
          ) : (
            <>
              <PrimaryActionButton
                type="button"
                id="advanced-filter-clear"
                name="advancedFilterClear"
                data-filter-field="clear-filters"
                variant="outline"
                onClick={clearFilters}
                style={{
                  marginLeft: 0,
                  minWidth: 'auto',
                  height: '40px',
                  padding: '8px 12px',
                  borderRadius: '8px',
                  border: '1px solid #6D3856',
                }}
                textStyle={{
                  ...buttonTextStyle,
                  color: '#6D3856',
                }}
              >
                {clearLabel}
              </PrimaryActionButton>
              <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
                <PrimaryActionButton
                  type="button"
                  id="advanced-filter-cancel"
                  name="advancedFilterCancel"
                  data-filter-field="cancel"
                  variant="outline"
                  onClick={() => {
                    onCancel?.();
                    onClose?.();
                  }}
                  style={{
                    marginLeft: 0,
                    minWidth: 'auto',
                    height: '40px',
                    padding: '8px 12px',
                    borderRadius: '8px',
                    border: '1px solid #38656D',
                  }}
                  textStyle={{
                    ...buttonTextStyle,
                    color: '#38656D',
                  }}
                >
                  {cancelLabel}
                </PrimaryActionButton>
                <PrimaryActionButton
                  type="button"
                  id="advanced-filter-apply"
                  name="advancedFilterApply"
                  data-filter-field="apply"
                  variant="primary"
                  onClick={() => {
                    onApply?.({ aiValue: currentAiValue, conditions: currentConditions });
                    onClose?.();
                  }}
                  style={{
                    marginLeft: 0,
                    minWidth: 'auto',
                    height: '40px',
                    padding: '8px 14px',
                    borderRadius: '8px',
                    border: '1px solid #38656D',
                    background: '#38656D',
                  }}
                  textStyle={{
                    ...buttonTextStyle,
                    color: '#FFFFFF',
                  }}
                >
                  {applyLabel}
                </PrimaryActionButton>
              </div>
            </>
          ))}
        </div>
      </div>
    </div>
  );
};

export default FiltrosAvanzados;
