import { useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
import { useQuery } from '@tanstack/react-query';

import {
  getStoredMaterialDrafts,
  saveStoredMaterialDrafts,
} from '@/lib/materialDraftStorage';
import { fetchMaterials } from '@/services/materialService';
import type { ProcurementMaterial } from '@/types';

export interface UseMaterialsListResult {
  /** 本地 draft + Supabase 已落表的物料合并后的最终展示列表 */
  materials: ProcurementMaterial[];
  /** 仅 Supabase 已落表的物料（react-query 缓存值） */
  supabaseMaterials: ProcurementMaterial[];
  /** 仅本地未落表的 draft（来自上传中暂存或本地缓存） */
  uploadedMaterials: ProcurementMaterial[];
  /** 修改本地 drafts；变动会自动同步到 localStorage */
  setUploadedMaterials: Dispatch<SetStateAction<ProcurementMaterial[]>>;
}

/**
 * 主物料列表的统一数据源。
 *
 * 内部职责：
 *   1. 从 localStorage 初始化本地 draft 列表，并在变动时回写
 *   2. 通过 react-query 拉取 Supabase 已落表的物料（缓存键 `['materials-supabase']`）
 *   3. 把两者按"draft 在前"的顺序合并暴露
 *
 * 调用方需要做单条 mutate（增删改）时，仍可直接使用 `useQueryClient()` 操作
 * `['materials-supabase']` 缓存或修改 `setUploadedMaterials`。
 */
export function useMaterialsList(): UseMaterialsListResult {
  const [uploadedMaterials, setUploadedMaterials] = useState<ProcurementMaterial[]>(
    () => getStoredMaterialDrafts(),
  );

  useEffect(() => {
    saveStoredMaterialDrafts(uploadedMaterials);
  }, [uploadedMaterials]);

  const { data: supabaseMaterials = [] } = useQuery({
    queryKey: ['materials-supabase'],
    queryFn: () => fetchMaterials(),
  });

  const materials = useMemo(
    () => [...uploadedMaterials, ...supabaseMaterials],
    [supabaseMaterials, uploadedMaterials],
  );

  return {
    materials,
    supabaseMaterials,
    uploadedMaterials,
    setUploadedMaterials,
  };
}
