import { useState, useCallback } from "react";
import { isSuccess } from "@/utils";
import type { TKnowledgeItem } from "@/types/knowledge";
import {
  getEntKnowledgeList,
  getKnowledgeList,
} from "@/service/knowledge";
import { EKnowlegeTypes } from "@/consts/enum";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
export interface UseKnowledgeHook {
  
  list: TKnowledgeItem[];
  isLoading: boolean;
  checkedValue: TKnowledgeItem[],
  listTypes?: EKnowlegeTypes[];
  loadMore: () => void;
  initLoad: () => void;
  setListTypes: (types: EKnowlegeTypes[]) => void;
  setCheckedValue: React.Dispatch<React.SetStateAction<TKnowledgeItem[]>>;
}

export function useKnowledge({entId, types = []}: {entId?: string|number, types?: EKnowlegeTypes[]}): UseKnowledgeHook {
  
  const fetcher = async ([url, {nextId, pageSize}])=> {
    if(entId !== undefined){
      const response = await getEntKnowledgeList({startId: nextId, entId, types, pageSize })
      return response.data
    }
    const response = await getKnowledgeList({startId: nextId, types, pageSize })
    return response.data
  }

  const {list, isLoading, loadMore, mutate} = useLoadMoreInfinite<TKnowledgeItem[]>(
    createKey(`${entId ? getEntKnowledgeList : getKnowledgeList}`),
    fetcher
  )
  const [listTypes, setListTypesState] = useState<EKnowlegeTypes[]>(types);
  const [checkedValue, setCheckedValue] = useState<TKnowledgeItem[]>([]);

  const initLoad = ()=> {
    mutate(undefined, {revalidate: true})
    setCheckedValue([])
    setListTypesState([])
  }

  const setListTypes = useCallback((types: EKnowlegeTypes[]) => {
    setListTypesState(types);
  }, []);

  return {
    list,
    isLoading,
    listTypes,
    checkedValue,
    initLoad,
    loadMore,
    setListTypes,
    setCheckedValue,
  };
}
