import { useTranslation } from 'react-i18next';

import { useRevealOnExpand } from '../../../hooks/useRevealOnExpand';
import type { TravelTimeEntry, TransportMode } from '../../../hooks/useTravelTime';
import type { FeatureMeta } from '../../../types';
import { ChevronIcon } from '../../ui/icons';
import FeatureBrowser from '../FeatureBrowser';
import { SPECIFIC_CRIMES_FILTER_NAME, isSpecificCrimeFilterName } from '../../../lib/crime-filter';
import {
  CRIME_SEVERITY_FILTER_NAMES,
  getCrimeSeverityFilterName,
  isCrimeSeverityFilterName,
  type CrimeSeverityFilterName,
} from '../../../lib/crime-severity-filter';
import {
  ELECTION_VOTE_SHARE_FILTER_NAME,
  isElectionVoteShareFilterName,
} from '../../../lib/election-filter';
import { ETHNICITIES_FILTER_NAME, isEthnicityFilterName } from '../../../lib/ethnicity-filter';
import {
  QUALIFICATIONS_FILTER_NAME,
  isQualificationFilterName,
} from '../../../lib/qualification-filter';
import { TENURE_FILTER_NAME, isTenureFilterName } from '../../../lib/tenure-filter';
import { SCHOOL_FILTER_NAME, isSchoolFilterName } from '../../../lib/school-filter';
import {
  POI_DISTANCE_FILTER_NAME,
  POI_FILTER_NAMES,
  getPoiFilterName,
  isPoiDistanceFilterName,
  type PoiFilterName,
} from '../../../lib/poi-distance-filter';

interface AddFilterPanelProps {
  collapsed: boolean;
  isLoggedIn: boolean;
  isLicensed: boolean;
  availableFeatures: FeatureMeta[];
  allFeatures: FeatureMeta[];
  pinnedFeature: string | null;
  defaultSchoolFeatureName: string | null;
  defaultSpecificCrimeFeatureName: string | null;
  defaultCrimeSeverityFeatureNames: Record<CrimeSeverityFilterName, string | null>;
  defaultElectionVoteShareFeatureName: string | null;
  defaultEthnicityFeatureName: string | null;
  defaultQualificationFeatureName: string | null;
  defaultTenureFeatureName: string | null;
  defaultPoiFilterFeatureNames: Record<PoiFilterName, string | null>;
  openInfoFeature?: string | null;
  travelTimeEntries: TravelTimeEntry[];
  onToggleCollapsed: () => void;
  onAddFilter: (name: string) => void;
  onTogglePin: (name: string) => void;
  onNavigateToSource?: (slug: string, featureName: string) => void;
  onClearOpenInfoFeature?: () => void;
  onAddTravelTimeEntry: (mode: TransportMode) => void;
  onUpgradeClick?: () => void;
  /** Anonymous-only: open the register prompt from the create-account nag. */
  onRegisterClick?: () => void;
}

export function AddFilterPanel({
  collapsed,
  isLoggedIn,
  isLicensed,
  availableFeatures,
  allFeatures,
  pinnedFeature,
  defaultSchoolFeatureName,
  defaultSpecificCrimeFeatureName,
  defaultCrimeSeverityFeatureNames,
  defaultElectionVoteShareFeatureName,
  defaultEthnicityFeatureName,
  defaultQualificationFeatureName,
  defaultTenureFeatureName,
  defaultPoiFilterFeatureNames,
  openInfoFeature,
  travelTimeEntries,
  onToggleCollapsed,
  onAddFilter,
  onTogglePin,
  onNavigateToSource,
  onClearOpenInfoFeature,
  onAddTravelTimeEntry,
  onUpgradeClick,
  onRegisterClick,
}: AddFilterPanelProps) {
  const { t } = useTranslation();
  const { setContainer, registerGroup, onToggle: revealGroupOnToggle } = useRevealOnExpand();

  const browserPinnedFeature =
    pinnedFeature && isSchoolFilterName(pinnedFeature)
      ? SCHOOL_FILTER_NAME
      : pinnedFeature && isSpecificCrimeFilterName(pinnedFeature)
        ? SPECIFIC_CRIMES_FILTER_NAME
        : pinnedFeature && isElectionVoteShareFilterName(pinnedFeature)
          ? ELECTION_VOTE_SHARE_FILTER_NAME
          : pinnedFeature && isEthnicityFilterName(pinnedFeature)
            ? ETHNICITIES_FILTER_NAME
            : pinnedFeature && isQualificationFilterName(pinnedFeature)
              ? QUALIFICATIONS_FILTER_NAME
              : pinnedFeature && isTenureFilterName(pinnedFeature)
                ? TENURE_FILTER_NAME
                : pinnedFeature && isPoiDistanceFilterName(pinnedFeature)
                  ? (getPoiFilterName(pinnedFeature) ?? POI_DISTANCE_FILTER_NAME)
                  : pinnedFeature && isCrimeSeverityFilterName(pinnedFeature)
                    ? (getCrimeSeverityFilterName(pinnedFeature) ?? pinnedFeature)
                    : pinnedFeature;

  const handleTogglePin = (name: string) => {
    if (name === SCHOOL_FILTER_NAME) {
      if (defaultSchoolFeatureName) onTogglePin(defaultSchoolFeatureName);
      return;
    }
    if (name === SPECIFIC_CRIMES_FILTER_NAME) {
      if (defaultSpecificCrimeFeatureName) onTogglePin(defaultSpecificCrimeFeatureName);
      return;
    }
    if (name === ELECTION_VOTE_SHARE_FILTER_NAME) {
      if (defaultElectionVoteShareFeatureName) onTogglePin(defaultElectionVoteShareFeatureName);
      return;
    }
    if (name === ETHNICITIES_FILTER_NAME) {
      if (defaultEthnicityFeatureName) onTogglePin(defaultEthnicityFeatureName);
      return;
    }
    if (name === QUALIFICATIONS_FILTER_NAME) {
      if (defaultQualificationFeatureName) onTogglePin(defaultQualificationFeatureName);
      return;
    }
    if (name === TENURE_FILTER_NAME) {
      if (defaultTenureFeatureName) onTogglePin(defaultTenureFeatureName);
      return;
    }
    if (CRIME_SEVERITY_FILTER_NAMES.includes(name as CrimeSeverityFilterName)) {
      const defaultSeverityFeatureName =
        defaultCrimeSeverityFeatureNames[name as CrimeSeverityFilterName];
      if (defaultSeverityFeatureName) onTogglePin(defaultSeverityFeatureName);
      return;
    }
    if (POI_FILTER_NAMES.includes(name as PoiFilterName)) {
      const defaultPoiFeatureName = defaultPoiFilterFeatureNames[name as PoiFilterName];
      if (defaultPoiFeatureName) onTogglePin(defaultPoiFeatureName);
      return;
    }
    onTogglePin(name);
  };

  return (
    <div
      className={`flex flex-col md:min-h-0 border-t border-warm-200 dark:border-warm-700 ${
        collapsed && isLicensed ? 'md:[flex:0_0_auto]' : 'md:[flex:1_1_0]'
      }`}
    >
      <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"
      >
        <span className="text-sm font-bold text-navy-950 dark:text-warm-100">
          {t('filters.addFilter')}
        </span>
        <ChevronIcon
          direction={collapsed ? 'down' : 'up'}
          className="w-4 h-4 text-warm-500 dark:text-warm-300"
        />
      </button>
      {(!collapsed || !isLicensed) && (
        <div className="flex min-h-0 flex-1 flex-col">
          {!collapsed && (
            <div ref={setContainer} className="min-h-0 flex-1 overflow-y-auto md:min-h-[12rem]">
              <FeatureBrowser
                availableFeatures={availableFeatures}
                allFeatures={allFeatures}
                pinnedFeature={browserPinnedFeature}
                onAddFilter={onAddFilter}
                onTogglePin={handleTogglePin}
                onNavigateToSource={onNavigateToSource}
                openInfoFeature={openInfoFeature}
                onClearOpenInfoFeature={onClearOpenInfoFeature}
                travelTimeEntries={travelTimeEntries}
                onAddTravelTimeEntry={onAddTravelTimeEntry}
                registerGroup={registerGroup}
                onGroupToggle={revealGroupOnToggle}
              />
            </div>
          )}
          {!isLicensed && (
            <div className="mt-auto shrink-0 flex flex-col items-center gap-2 px-3 pt-3 pb-2.5 border-t border-warm-200 dark:border-warm-700">
              <p className="text-sm text-warm-600 dark:text-warm-400 text-center leading-snug">
                {isLoggedIn ? t('filters.upgradePrompt') : t('filters.registerPrompt')}{' '}
                <span className="text-xs text-warm-400 dark:text-warm-500">
                  {isLoggedIn ? t('filters.oneTimeLifetime') : t('filters.registerSubPrompt')}
                </span>
              </p>
              <button
                onClick={isLoggedIn ? onUpgradeClick : onRegisterClick}
                className="w-full px-5 py-2 rounded-lg bg-gradient-to-r from-teal-500 to-teal-600 hover:from-teal-600 hover:to-teal-700 text-white font-medium text-sm shadow-sm hover:shadow-md"
              >
                {isLoggedIn ? t('filters.upgradeToFullMap') : t('filters.registerCta')}
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
