import { useTranslation } from 'react-i18next';
import { Slider } from '../../ui/Slider';
import { FeatureActions } from '../../ui/FeatureIcons';
import { FeatureLabel } from '../../ui/FeatureLabel';
import type { FeatureFilters, FeatureMeta } from '../../../types';
import { formatNumber } from '../../../lib/format';
import {
  SCHOOL_FILTER_NAME,
  clampSchoolRange,
  getSchoolBackendFeatureName,
  getSchoolFilterConfig,
  getSchoolFilterMeta,
  replaceSchoolFilterKeySelection,
  type SchoolPhase,
  type SchoolRating,
} from '../../../lib/school-filter';
import { SliderLabels } from './SliderLabels';

export function SchoolFilterCard({
  features,
  schoolFeature,
  filters,
  activeFeature,
  dragValue,
  pinnedFeature,
  filterImpact,
  onFilterChange,
  onDragStart,
  onDragChange,
  onDragEnd,
  onTogglePin,
  onShowInfo,
  onRemove,
}: {
  features: FeatureMeta[];
  schoolFeature: FeatureMeta;
  filters: FeatureFilters;
  activeFeature: string | null;
  dragValue: [number, number] | null;
  pinnedFeature: string | null;
  filterImpact?: number;
  onFilterChange: (name: string, value: [number, number] | string[]) => void;
  onDragStart: (name: string, initialValue?: [number, number]) => void;
  onDragChange: (value: [number, number]) => void;
  onDragEnd: () => void;
  onTogglePin: (name: string) => void;
  onShowInfo: (feature: FeatureMeta) => void;
  onRemove: () => void;
}) {
  const { t } = useTranslation();
  const config = getSchoolFilterConfig(schoolFeature.name);
  const schoolMeta = getSchoolFilterMeta(features);
  const backendFeature = config
    ? features.find((feature) => feature.name === config.featureName)
    : undefined;
  const isActive = activeFeature === schoolFeature.name;
  const isPinned = pinnedFeature === schoolFeature.name;
  const hist = backendFeature?.histogram;
  const dataMin = hist?.min ?? backendFeature?.min ?? 0;
  const dataMax = hist?.max ?? backendFeature?.max ?? 10;
  const displayValue =
    isActive && dragValue
      ? dragValue
      : (filters[schoolFeature.name] as [number, number]) || [dataMin, dataMax];
  const sliderValue: [number, number] = [
    displayValue[0] <= dataMin ? (backendFeature?.min ?? dataMin) : displayValue[0],
    displayValue[1] >= dataMax ? (backendFeature?.max ?? dataMax) : displayValue[1],
  ];

  if (!config) return null;

  const replaceSchoolFeature = (
    next: Partial<{
      phase: SchoolPhase;
      rating: SchoolRating;
    }>
  ) => {
    const nextName = replaceSchoolFilterKeySelection(schoolFeature.name, next);
    if (nextName === schoolFeature.name) return;

    const nextBackendName = getSchoolBackendFeatureName(nextName);
    const nextFeature = nextBackendName
      ? features.find((feature) => feature.name === nextBackendName)
      : undefined;
    const nextDataMin = nextFeature?.histogram?.min ?? nextFeature?.min ?? 0;
    const nextDataMax = nextFeature?.histogram?.max ?? nextFeature?.max ?? Math.max(1, dataMax);
    const nextRange = clampSchoolRange(
      [
        displayValue[0] <= dataMin ? nextDataMin : displayValue[0],
        displayValue[1] >= dataMax ? nextDataMax : displayValue[1],
      ],
      nextFeature
    );
    onFilterChange(nextName, nextRange);
    if (isPinned) onTogglePin(nextName);
  };

  const segmentedClass =
    'grid grid-cols-2 overflow-hidden rounded-md border border-warm-200 dark:border-warm-700 bg-warm-50 dark:bg-warm-800';
  const optionClass = (active: boolean) =>
    `px-2 py-1 text-xs font-medium border-r last:border-r-0 border-warm-200 dark:border-warm-700 transition-colors ${
      active
        ? 'bg-teal-600 text-white dark:bg-teal-500'
        : 'text-warm-600 hover:bg-warm-100 dark:text-warm-300 dark:hover:bg-warm-700'
    }`;

  return (
    <div
      data-filter-name={SCHOOL_FILTER_NAME}
      className={`space-y-1.5 px-2 py-1.5 rounded ${isActive ? 'ring-2 ring-teal-400 bg-teal-50 dark:bg-teal-900/30' : isPinned ? 'ring-2 ring-teal-400 bg-teal-50/50 dark:bg-teal-900/20' : ''}`}
    >
      <div className="relative z-10 flex items-center justify-between gap-1">
        <FeatureLabel
          feature={schoolMeta}
          size="sm"
          className="min-w-0 shrink"
          hideIconOnMobile
          wrap
        />
        <FeatureActions
          feature={schoolMeta}
          isPinned={isPinned}
          isPreviewing={isActive}
          onTogglePin={() => onTogglePin(schoolFeature.name)}
          onShowInfo={() => onShowInfo(schoolMeta)}
          onRemove={onRemove}
        />
      </div>

      <div className="space-y-1.5">
        <div>
          <div className="mb-0.5 text-[10px] font-medium uppercase text-warm-400 dark:text-warm-500">
            {t('filters.schoolType')}
          </div>
          <div className={segmentedClass} role="radiogroup" aria-label={t('filters.schoolType')}>
            <button
              type="button"
              role="radio"
              aria-checked={config.phase === 'primary'}
              onClick={() => replaceSchoolFeature({ phase: 'primary' })}
              className={optionClass(config.phase === 'primary')}
            >
              {t('filters.primary')}
            </button>
            <button
              type="button"
              role="radio"
              aria-checked={config.phase === 'secondary'}
              onClick={() => replaceSchoolFeature({ phase: 'secondary' })}
              className={optionClass(config.phase === 'secondary')}
            >
              {t('filters.secondary')}
            </button>
          </div>
        </div>
        <div>
          <div className="mb-0.5 text-[10px] font-medium uppercase text-warm-400 dark:text-warm-500">
            {t('filters.rating')}
          </div>
          <div className={segmentedClass} role="radiogroup" aria-label={t('filters.schoolRating')}>
            <button
              type="button"
              role="radio"
              aria-checked={config.rating === 'good'}
              onClick={() => replaceSchoolFeature({ rating: 'good' })}
              className={optionClass(config.rating === 'good')}
            >
              {t('filters.goodPlus')}
            </button>
            <button
              type="button"
              role="radio"
              aria-checked={config.rating === 'outstanding'}
              onClick={() => replaceSchoolFeature({ rating: 'outstanding' })}
              className={optionClass(config.rating === 'outstanding')}
            >
              {t('filters.outstanding')}
            </button>
          </div>
        </div>
      </div>

      <Slider
        min={backendFeature?.min ?? dataMin}
        max={backendFeature?.max ?? dataMax}
        step={backendFeature?.step ?? 1}
        value={sliderValue}
        onValueChange={([min, max]) =>
          onDragChange([
            min <= (backendFeature?.min ?? dataMin) ? dataMin : min,
            max >= (backendFeature?.max ?? dataMax) ? dataMax : max,
          ])
        }
        onPointerDown={() => onDragStart(schoolFeature.name, displayValue)}
        onPointerUp={() => onDragEnd()}
      />
      <SliderLabels
        min={backendFeature?.min ?? dataMin}
        max={backendFeature?.max ?? dataMax}
        value={sliderValue}
        displayValues={displayValue}
        isAtMin={displayValue[0] === dataMin}
        isAtMax={displayValue[1] === dataMax}
        raw={backendFeature?.raw}
        feature={backendFeature}
        onValueChange={(v) => onFilterChange(schoolFeature.name, v)}
      />
      {filterImpact != null && filterImpact > 0 && (
        <p className="text-[10px] text-warm-400 dark:text-warm-500 -mt-1 ml-2.5">
          {t('filters.filtersOut', { value: formatNumber(filterImpact) })}
        </p>
      )}
    </div>
  );
}
