import { useTranslation } from 'react-i18next';
import { FONT_FAMILY_MONO, FONT_FAMILY_SANS } from '../../../designTokens';

const getFilterLabel = (filter) => {
  if (filter === null || filter === undefined) return '';
  if (typeof filter === 'string' || typeof filter === 'number') return String(filter);
  if (typeof filter === 'object') {
    if (filter.label !== undefined) return String(filter.label);
    if (filter.name !== undefined) return String(filter.name);
    const hasConditionMetadata = filter.field !== undefined && filter.operator !== undefined;
    if (hasConditionMetadata) {
      const fieldLabel =
        typeof filter.field === 'object'
          ? String(filter.field.label ?? filter.field.name ?? filter.field.value ?? '')
          : String(filter.field ?? '');
      const operatorLabel =
        typeof filter.operator === 'object'
          ? String(filter.operator.label ?? filter.operator.name ?? filter.operator.value ?? '')
          : String(filter.operator ?? '');
      const rangeValue = filter.value && typeof filter.value === 'object'
        ? { from: filter.value.from ?? '', to: filter.value.to ?? '' }
        : { from: filter.valueFrom ?? '', to: filter.valueTo ?? '' };
      if (rangeValue.from || rangeValue.to) {
        const separator = rangeValue.from && rangeValue.to ? ' - ' : '';
        return `${fieldLabel} ${operatorLabel} ${rangeValue.from}${separator}${rangeValue.to}`.trim();
      }
      return `${fieldLabel} ${operatorLabel} ${String(filter.value ?? '')}`.trim();
    }
    if (typeof filter.value === 'string' || typeof filter.value === 'number') return String(filter.value);
    return String(filter.id ?? '');
  }
  return '';
};

const getFilterKey = (filter, index) => {
  if (filter && typeof filter === 'object' && (filter.id !== undefined || filter.key !== undefined)) {
    return filter.id ?? filter.key;
  }
  return `${getFilterLabel(filter)}-${index}`;
};

export const AppliedFilters = ({
  filters = [],
  appliedFilters,
  onFilterRemove,
  onAppliedFilterRemove,
  onClear,
  onAppliedFiltersClear,
  showLabel = true,
  showAppliedFiltersLabel,
  label,
  appliedFiltersLabel,
  clearLabel,
  appliedFiltersClearLabel,
  className = '',
  style,
}) => {
  const { t } = useTranslation();
  const resolvedFilters = Array.isArray(appliedFilters) ? appliedFilters : filters;
  const resolvedShowLabel = showAppliedFiltersLabel ?? showLabel;
  const resolvedLabel = appliedFiltersLabel ?? label ?? t('table.appliedFiltersLabel', { defaultValue: 'Filtros aplicados' });
  const resolvedClearLabel = appliedFiltersClearLabel ?? clearLabel ?? t('table.clearFilters', { defaultValue: 'Limpiar filtros' });
  const handleRemove = onAppliedFilterRemove ?? onFilterRemove;
  const handleClear = onAppliedFiltersClear ?? onClear;

  if (!Array.isArray(resolvedFilters) || resolvedFilters.length === 0) return null;

  return (
    <div
      className={`anima-applied-filters ${className}`}
      style={{
        width: '100%',
        minWidth: 0,
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
        gap: '16px',
        boxSizing: 'border-box',
        ...(style || {}),
      }}
    >
      <style>{`
        @media (max-width: 768px) {
          .anima-applied-filters {
            display: grid !important;
            grid-template-columns: minmax(0, 1fr) auto !important;
            column-gap: 16px !important;
            row-gap: 8px !important;
            align-items: start !important;
          }
          .anima-applied-filters__content {
            display: contents !important;
          }
          .anima-applied-filters__title {
            grid-column: 1 !important;
            grid-row: 1 !important;
          }
          .anima-applied-filters__clear {
            grid-column: 2 !important;
            grid-row: 1 !important;
          }
          .anima-applied-filters__chips {
            grid-column: 1 / -1 !important;
            grid-row: 2 !important;
            width: 100% !important;
            max-width: 100% !important;
            min-width: 0 !important;
            flex-wrap: nowrap !important;
            overflow-x: auto !important;
            overflow-y: hidden !important;
            scrollbar-width: none !important;
            -ms-overflow-style: none !important;
            padding-bottom: 2px !important;
          }
          .anima-applied-filters__chips::-webkit-scrollbar {
            display: none !important;
          }
          .anima-applied-filters__chip {
            flex: 0 0 auto !important;
          }
        }
      `}</style>
      <div
        className="anima-applied-filters__content"
        style={{ minWidth: 0, display: 'flex', flexDirection: 'column', gap: '8px' }}
      >
        {resolvedShowLabel && (
          <span
            className="anima-applied-filters__title"
            style={{
              fontFamily: FONT_FAMILY_SANS,
              fontWeight: 400,
              fontSize: '12px',
              lineHeight: '18px',
              letterSpacing: '0.08em',
              color: '#474747',
              textTransform: 'uppercase',
            }}
          >
            {resolvedLabel}
          </span>
        )}
        <div className="anima-applied-filters__chips" style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
          {resolvedFilters.map((filter, index) => {
            const filterLabel = getFilterLabel(filter);
            if (!filterLabel) return null;
            return (
              <button
                className="anima-applied-filters__chip"
                key={getFilterKey(filter, index)}
                type="button"
                onClick={() => handleRemove?.(filter)}
                style={{
                  height: '28px',
                  borderRadius: '999px',
                  border: '1px solid #6D3856',
                  background: '#FFFFFF',
                  padding: '4px 10px',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: '8px',
                  boxSizing: 'border-box',
                  color: '#6D3856',
                  fontFamily: FONT_FAMILY_MONO,
                  fontWeight: 400,
                  fontSize: '12px',
                  lineHeight: '18px',
                  cursor: handleRemove ? 'pointer' : 'default',
                }}
                aria-label={t('table.removeAppliedFilterAria', {
                  defaultValue: 'Quitar filtro {{filter}}',
                  filter: filterLabel,
                })}
              >
                <span>{filterLabel}</span>
                {handleRemove && <span aria-hidden style={{ fontSize: '18px', lineHeight: '16px' }}>×</span>}
              </button>
            );
          })}
        </div>
      </div>
      {handleClear && (
        <button
          type="button"
          className="anima-applied-filters__clear"
          onClick={handleClear}
          style={{
            border: 'none',
            background: 'transparent',
            padding: 0,
            color: '#6D3856',
            fontFamily: FONT_FAMILY_SANS,
            fontWeight: 600,
            fontSize: '12px',
            lineHeight: '18px',
            whiteSpace: 'nowrap',
            cursor: 'pointer',
          }}
        >
          {resolvedClearLabel}
        </button>
      )}
    </div>
  );
};

export default AppliedFilters;
