import { useMemo } from 'react';

import type { ProcurementMaterial } from '@/types';

export type MaterialSortDir = 'asc' | 'desc';

export interface MaterialFilterInputs {
  /** 批次精确匹配 */
  batchId?: string;
  /** 来源文件 substring（不区分大小写） */
  sourceFile?: string;
  /** 物料名称 substring（不区分大小写） */
  name?: string;
  /** 创建人 substring（不区分大小写） */
  createdBy?: string;
  /** 创建时间下界（YYYY-MM-DD，含） */
  createdAtFrom?: string;
  /** 创建时间上界（YYYY-MM-DD，含） */
  createdAtTo?: string;
  /** 排序字段；不传则保持入参顺序 */
  sortKey?: string | null;
  /** 排序方向，默认 asc */
  sortDir?: MaterialSortDir;
}

function compareMaterialField(
  a: ProcurementMaterial,
  b: ProcurementMaterial,
  key: keyof ProcurementMaterial,
): number {
  const va = a[key];
  const vb = b[key];
  if (va == null) return 1;
  if (vb == null) return -1;
  if (typeof va === 'number' && typeof vb === 'number') {
    return va - vb;
  }
  return String(va).localeCompare(String(vb));
}

/**
 * 根据 `filters` 对物料数组做客户端过滤 + 排序。所有筛选条件都是 AND 关系。
 *
 * 设计目的：把 Materials.tsx 的本地筛选逻辑抽离成可独立测试的 hook。
 * 调用方仍持有原始 `materials` 数组与各个 search state，本 hook 仅负责聚合
 * 与计算，不维护任何状态。
 */
export function useFilteredMaterials(
  materials: ProcurementMaterial[],
  filters: MaterialFilterInputs,
): ProcurementMaterial[] {
  const {
    batchId,
    sourceFile,
    name,
    createdBy,
    createdAtFrom,
    createdAtTo,
    sortKey,
    sortDir = 'asc',
  } = filters;

  return useMemo(() => {
    let next = materials;

    if (batchId) {
      next = next.filter(m => m.batch_id === batchId);
    }
    if (sourceFile) {
      const needle = sourceFile.toLowerCase();
      next = next.filter(m => m.source_file.toLowerCase().includes(needle));
    }
    if (name) {
      const needle = name.toLowerCase();
      next = next.filter(m => m.material_name.toLowerCase().includes(needle));
    }
    if (createdBy) {
      const needle = createdBy.toLowerCase();
      next = next.filter(m => (m.created_by || '').toLowerCase().includes(needle));
    }
    if (createdAtFrom) {
      next = next.filter(m => m.created_at && m.created_at.slice(0, 10) >= createdAtFrom);
    }
    if (createdAtTo) {
      next = next.filter(m => m.created_at && m.created_at.slice(0, 10) <= createdAtTo);
    }

    if (sortKey) {
      // 仅排序时复制一份，避免污染入参引用
      next = [...next].sort((a, b) => {
        const cmp = compareMaterialField(a, b, sortKey as keyof ProcurementMaterial);
        return sortDir === 'asc' ? cmp : -cmp;
      });
    }

    return next;
  }, [materials, batchId, sourceFile, name, createdBy, createdAtFrom, createdAtTo, sortKey, sortDir]);
}
