import type { RefObject } from 'react';
import { useTranslation } from 'react-i18next';

import type { AiFilterErrorType } from '../../../hooks/useAiFilters';
import type { TravelTimeEntry } from '../../../hooks/useTravelTime';
import type { PercentileScale } from '../../../lib/format';
import type { FeatureFilters, FeatureMeta } from '../../../types';
import { ChevronIcon, LightbulbIcon } from '../../ui/icons';
import AiFilterInput from '../AiFilterInput';
import { ActiveFilterList } from './ActiveFilterList';

interface ActiveFiltersPanelProps {
  scrollRef: RefObject<HTMLDivElement | null>;
  collapsed: boolean;
  addFiltersExpanded: boolean;
  badgeCount: number;
  activeEntryCount: number;
  features: FeatureMeta[];
  filters: FeatureFilters;
  enabledFeatureList: FeatureMeta[];
  activeFeature: string | null;
  dragValue: [number, number] | null;
  pinnedFeature: string | null;
  travelTimeEntries: TravelTimeEntry[];
  filterImpacts?: Record<string, number>;
  percentileScales: Map<string, PercentileScale>;
  destinationDropdownPortal: boolean;
  isGroupExpanded: (name: string) => boolean;
  onToggleGroup: (name: string) => void;
  aiFilterLoading: boolean;
  aiFilterError: string | null;
  aiFilterErrorType: AiFilterErrorType | null;
  aiFilterNotes: string | null;
  aiFilterSummary: string | null;
  isLoggedIn: boolean;
  onToggleCollapsed: () => void;
  onClearAllClick: () => void;
  onShowPhilosophy: () => void;
  onAiFilterSubmit: (query: string) => void;
  onLoginRequired: () => void;
  onFilterChange: (name: string, value: [number, number] | string[]) => void;
  onRemoveFilter: (name: string) => void;
  onDragStart: (name: string, initialValue?: [number, number]) => void;
  onDragChange: (value: [number, number]) => void;
  onDragEnd: () => void;
  onTogglePin: (name: string) => void;
  onShowInfo: (feature: FeatureMeta) => void;
  onTravelTimeRemoveEntry: (index: number) => void;
  onTravelTimeSetDestination: (
    index: number,
    slug: string,
    label: string,
    lat: number,
    lon: number
  ) => void;
  onTravelTimeRangeChange: (index: number, range: [number, number]) => void;
  onTravelTimeDragEnd: (index: number) => void;
  onTravelTimeToggleBest: (index: number) => void;
  onTravelTimeToggleNoChange: (index: number) => void;
  onTravelTimeToggleOneChange: (index: number) => void;
  onTravelTimeToggleNoBuses: (index: number) => void;
}

export function ActiveFiltersPanel({
  scrollRef,
  collapsed,
  addFiltersExpanded,
  badgeCount,
  activeEntryCount,
  features,
  filters,
  enabledFeatureList,
  activeFeature,
  dragValue,
  pinnedFeature,
  travelTimeEntries,
  filterImpacts,
  percentileScales,
  destinationDropdownPortal,
  isGroupExpanded,
  onToggleGroup,
  aiFilterLoading,
  aiFilterError,
  aiFilterErrorType,
  aiFilterNotes,
  aiFilterSummary,
  isLoggedIn,
  onToggleCollapsed,
  onClearAllClick,
  onShowPhilosophy,
  onAiFilterSubmit,
  onLoginRequired,
  onFilterChange,
  onRemoveFilter,
  onDragStart,
  onDragChange,
  onDragEnd,
  onTogglePin,
  onShowInfo,
  onTravelTimeRemoveEntry,
  onTravelTimeSetDestination,
  onTravelTimeRangeChange,
  onTravelTimeDragEnd,
  onTravelTimeToggleBest,
  onTravelTimeToggleNoChange,
  onTravelTimeToggleOneChange,
  onTravelTimeToggleNoBuses,
}: ActiveFiltersPanelProps) {
  const { t } = useTranslation();

  return (
    <div
      className={`flex flex-col md:min-h-0 ${
        collapsed ? 'md:[flex:0_0_auto]' : 'md:[flex:0_1_auto]'
      } ${!collapsed && addFiltersExpanded ? 'md:max-h-[60%]' : ''}`}
    >
      <button
        onClick={onToggleCollapsed}
        className="shrink-0 flex items-center justify-between border-y border-teal-300 bg-teal-100 px-3 py-3 cursor-pointer hover:bg-teal-200 dark:border-teal-800 dark:bg-teal-900/50 dark:hover:bg-teal-900/70"
      >
        <div className="flex items-center gap-2">
          <span className="text-sm font-bold text-navy-950 dark:text-warm-100">
            {t('filters.activeFilters')}
          </span>
          {badgeCount > 0 && (
            <span className="rounded-full bg-teal-600 px-1.5 py-0.5 text-xs font-bold text-white ring-1 ring-teal-700 dark:bg-teal-300 dark:text-navy-950 dark:ring-teal-200">
              {badgeCount}
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          {badgeCount > 0 && (
            <span
              role="button"
              tabIndex={0}
              onClick={(e) => {
                e.stopPropagation();
                onClearAllClick();
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.stopPropagation();
                  onClearAllClick();
                }
              }}
              className="text-xs text-teal-700 underline hover:text-teal-900 dark:text-teal-300 dark:hover:text-teal-200"
            >
              {t('filters.clearAll')}
            </span>
          )}
          <ChevronIcon
            direction={collapsed ? 'down' : 'up'}
            className="w-4 h-4 text-warm-500 dark:text-warm-300"
          />
        </div>
      </button>

      {!collapsed && (
        <div ref={scrollRef} className="md:min-h-0 md:flex-1 md:overflow-y-auto overflow-x-hidden">
          <AiFilterInput
            loading={aiFilterLoading}
            error={aiFilterError}
            errorType={aiFilterErrorType}
            notes={aiFilterNotes}
            summary={aiFilterSummary}
            onSubmit={onAiFilterSubmit}
            isLoggedIn={isLoggedIn}
            onLoginRequired={onLoginRequired}
          />
          <div className="px-3 pb-2 space-y-2">
            <button
              onClick={onShowPhilosophy}
              className="w-full px-3 py-1.5 rounded-lg border border-warm-200 dark:border-warm-700 bg-white dark:bg-warm-800 hover:bg-warm-50 dark:hover:bg-warm-700 text-teal-600 dark:text-teal-400 font-medium text-sm flex items-center justify-center gap-2"
            >
              <LightbulbIcon />
              {t('filters.findingPerfectPostcode')}
            </button>
          </div>
          {enabledFeatureList.length === 0 && activeEntryCount === 0 && (
            <p className="px-3 py-1.5 text-xs text-warm-400 dark:text-warm-500">
              {t('filters.addFiltersHint')}
            </p>
          )}

          <ActiveFilterList
            features={features}
            filters={filters}
            enabledFeatureList={enabledFeatureList}
            activeFeature={activeFeature}
            dragValue={dragValue}
            pinnedFeature={pinnedFeature}
            travelTimeEntries={travelTimeEntries}
            filterImpacts={filterImpacts}
            percentileScales={percentileScales}
            destinationDropdownPortal={destinationDropdownPortal}
            isGroupExpanded={isGroupExpanded}
            onToggleGroup={onToggleGroup}
            onFilterChange={onFilterChange}
            onRemoveFilter={onRemoveFilter}
            onDragStart={onDragStart}
            onDragChange={onDragChange}
            onDragEnd={onDragEnd}
            onTogglePin={onTogglePin}
            onShowInfo={onShowInfo}
            onTravelTimeRemoveEntry={onTravelTimeRemoveEntry}
            onTravelTimeSetDestination={onTravelTimeSetDestination}
            onTravelTimeRangeChange={onTravelTimeRangeChange}
            onTravelTimeDragEnd={onTravelTimeDragEnd}
            onTravelTimeToggleBest={onTravelTimeToggleBest}
            onTravelTimeToggleNoChange={onTravelTimeToggleNoChange}
            onTravelTimeToggleOneChange={onTravelTimeToggleOneChange}
            onTravelTimeToggleNoBuses={onTravelTimeToggleNoBuses}
          />
        </div>
      )}
    </div>
  );
}
