// composables/useWeatherFilter.ts
import { ref, computed, type Ref } from "vue";
import { RAIN_FILTER_LEVELS, FILTER_KEYS, TEMP_FILTER_FIELDS, type TempFilterField } from "./useWeatherConstants";
import type { WeatherDataRow } from "./useWeatherStats";

// ---------- 类型 ----------

export interface NumericFilter {
  op: "" | "gte" | "lte" | "range";
  val: number;
  min: number;
  max: number;
}

export interface WeatherFilters {
  rainfall: NumericFilter;
  rainLevel: string[];
  tmaxF: NumericFilter;
  tminF: NumericFilter;
  tavgF: NumericFilter & { range?: undefined }; // tavgF 不支持 range
  yearRange: [number, number];
  decades: number[];
}

// ---------- 工厂 ----------

export function defaultNumericFilter(overrides?: Partial<NumericFilter>): NumericFilter {
  return { op: "", val: 0, min: 0, max: 999, ...overrides };
}

export function createDefaultFilters(
  startYear: number,
  endYear: number
): WeatherFilters {
  return {
    rainfall: { op: "", val: 25, min: 0, max: 999 },
    rainLevel: [],
    tmaxF: { op: "", val: 35, min: 25, max: 40 },
    tminF: { op: "", val: 5, min: 0, max: 15 },
    tavgF: { op: "", val: 20, min: 0, max: 999 },
    yearRange: [startYear, endYear],
    decades: []
  };
}

// ---------- 匹配逻辑 ----------

export function matchOp(val: number | null, cfg: NumericFilter | undefined): boolean {
  if (!cfg || !cfg.op) return true;
  // null 表示无数据，不参与任何数值筛选（既不匹配 ≥ 也不匹配 ≤）
  if (val == null) return false;
  const n = Number(val);
  if (isNaN(n)) return false;
  if (cfg.op === "gte") return n >= cfg.val;
  if (cfg.op === "lte") return n <= cfg.val;
  if (cfg.op === "range") return n >= (cfg.min ?? -Infinity) && n <= (cfg.max ?? Infinity);
  return true;
}

// ---------- Composable ----------

export interface UseWeatherFilterOptions {
  /** 当前数据起始年份（computed） */
  startYear: Ref<number> | (() => number);
  /** 当前数据结束年份（computed） */
  endYear: Ref<number> | (() => number);
}

export function useWeatherFilter(opts: UseWeatherFilterOptions) {
  const filterOpen = ref(false);
  const showOnlyFiltered = ref(false);

  const resolveStart = () =>
    typeof opts.startYear === "function" ? opts.startYear() : opts.startYear.value;
  const resolveEnd = () =>
    typeof opts.endYear === "function" ? opts.endYear() : opts.endYear.value;

  // 初始化 filters
  const filters = ref<WeatherFilters>(createDefaultFilters(resolveStart(), resolveEnd()));

  /** 同步年份 range 到 filters（数据变更时调用） */
  function syncYearRange(from: number, to: number) {
    filters.value.yearRange = [from, to];
  }

  /** 重置筛选条件 */
  function resetFilters() {
    filters.value = createDefaultFilters(resolveStart(), resolveEnd());
    showOnlyFiltered.value = false;
  }

  // ---------- 年代 ----------

  const availableDecades = computed(() => {
    const s = new Set<number>();
    for (let y = resolveStart(); y <= resolveEnd(); y++) {
      s.add(Math.floor(y / 10) * 10);
    }
    return Array.from(s).sort();
  });

  function toggleDecade(d: number) {
    const i = filters.value.decades.indexOf(d);
    if (i >= 0) {
      filters.value.decades.splice(i, 1);
    } else {
      filters.value.decades.push(d);
    }
  }

  // ---------- 雨量级别 ----------

  function toggleRainLevel(lv: { label: string; min: number; max: number }) {
    const idx = filters.value.rainLevel.indexOf(lv.label);
    if (idx >= 0) {
      filters.value.rainLevel.splice(idx, 1);
    } else {
      filters.value.rainLevel.push(lv.label);
    }
    syncRainfallFromLevels();
  }

  /** 当选中的雨量级别变更后，自动同步 rain.range */
  function syncRainfallFromLevels() {
    const labels = filters.value.rainLevel;
    if (labels.length === 0) {
      filters.value.rainfall.op = "";
      return;
    }
    let gmin = Infinity;
    let gmax = -Infinity;
    for (const def of RAIN_FILTER_LEVELS) {
      if (labels.includes(def.label)) {
        if (def.min < gmin) gmin = def.min;
        if (def.max > gmax) gmax = def.max;
      }
    }
    filters.value.rainfall = { op: "range", min: gmin, max: gmax, val: gmax };
  }

  // ---------- 筛选状态 ----------

  const hasActiveFilter = computed(() => {
    const f = filters.value;
    return (
      FILTER_KEYS.some((k) => f[k]?.op) ||
      f.rainLevel.length > 0 ||
      f.decades.length > 0
    );
  });

  const activeFilterCount = computed(() => {
    const f = filters.value;
    let c = FILTER_KEYS.filter((k) => f[k]?.op).length;
    if (f.rainLevel.length) c++;
    if (f.decades.length) c++;
    return c;
  });

  // ---------- 行匹配 ----------

  /** 判断单行是否命中筛选 */
  function rowMatchesFilter(row: WeatherDataRow, f: WeatherFilters): boolean {
    if (!matchOp(row.rainfall, f.rainfall)) return false;
    if (!matchOp(row.tmax, f.tmaxF)) return false;
    if (!matchOp(row.tmin, f.tminF)) return false;
    if (!matchOp(row.tavg, f.tavgF)) return false;
    if (f.decades.length > 0 && !f.decades.includes(Math.floor(row.year / 10) * 10)) return false;
    if (f.rainLevel.length > 0 && !f.rainLevel.includes(row._rainLevel ?? "")) return false;
    return true;
  }

  // ---------- 暴露导出 ----------

  return {
    // 状态
    filterOpen,
    showOnlyFiltered,
    filters,
    // 计算
    availableDecades,
    hasActiveFilter,
    activeFilterCount,
    // 方法
    syncYearRange,
    resetFilters,
    toggleDecade,
    toggleRainLevel,
    rowMatchesFilter,
    // 常量
    TEMP_FILTER_FIELDS,
    RAIN_FILTER_LEVELS
  };
}
