import { useMemo, useState } from 'react';
import { toEnglishDigits, tomanToRial } from '@/utils';
import { useDebouncedValue } from '@/services/search';
import { SEARCH_FILTER_DEBOUNCE_MS, SEARCH_PAGE_SIZE } from '@/services/search/constants';
import type { NurseGender, NurseSearchFilters } from '@/services/search/types';
import type { CascadingRegionValue } from '@/components/geography/CascadingRegionSelect';

const EMPTY_REGION: CascadingRegionValue = { provinceId: null, cityId: null, districtId: null };

/** Toman input → IRR-Rial digit-string at the field boundary; undefined for blank/invalid input. */
function tomanInputToIrr(toman: string): string | undefined {
  const digits = toEnglishDigits(toman).trim();
  if (!/^\d+$/.test(digits)) return undefined;
  return tomanToRial(digits);
}

/**
 * The C1 filter controller — fast-changing UI state kept **colocated** (not in a high context provider,
 * phase §5). Holds the category, cascading region, same-gender facet, and Toman price inputs, and
 * derives the canonical `NurseSearchFilters` that becomes the live-count query key and the C2 URL. The
 * price inputs are **debounced** so typing doesn't fan out one search per keystroke before the value
 * joins the query key. `districtId = null` (whole city) is carried as an omitted filter, never a bogus id.
 */
export function useSearchFilters(initialCategoryId?: number) {
  const [categoryId, setCategoryId] = useState<number | null>(initialCategoryId ?? null);
  const [region, setRegion] = useState<CascadingRegionValue>(EMPTY_REGION);
  const [gender, setGender] = useState<NurseGender | undefined>(undefined);
  const [priceMinToman, setPriceMinToman] = useState('');
  const [priceMaxToman, setPriceMaxToman] = useState('');
  const [dateIntent, setDateIntent] = useState('');

  const debouncedMin = useDebouncedValue(priceMinToman, SEARCH_FILTER_DEBOUNCE_MS);
  const debouncedMax = useDebouncedValue(priceMaxToman, SEARCH_FILTER_DEBOUNCE_MS);

  const filters: NurseSearchFilters = useMemo(
    () => ({
      serviceCategoryId: categoryId ?? 0,
      cityId: region.cityId ?? 0,
      districtId: region.districtId ?? undefined,
      nurseGender: gender,
      priceMin: tomanInputToIrr(debouncedMin),
      priceMax: tomanInputToIrr(debouncedMax),
      sort: 'rating',
      page: 1,
      pageSize: SEARCH_PAGE_SIZE,
    }),
    [categoryId, region.cityId, region.districtId, gender, debouncedMin, debouncedMax],
  );

  const isReady = filters.serviceCategoryId > 0 && filters.cityId > 0;

  return {
    categoryId,
    setCategoryId,
    region,
    setRegion,
    gender,
    setGender,
    priceMinToman,
    setPriceMinToman,
    priceMaxToman,
    setPriceMaxToman,
    dateIntent,
    setDateIntent,
    filters,
    isReady,
  };
}
