import { useState, useEffect, useCallback } from 'react';
import knowledgeService from '@/services/knowledge_service';
import type { IChunk, IChunkListResult } from '@/interfaces/database/knowledge';
import type { IFetchChunkListRequestBody } from '@/interfaces/request/knowledge';

// Chunk列表Hook状态接口
export interface UseChunkListState {
  chunks: IChunk[];
  total: number;
  loading: boolean;
  error: string | null;
  currentPage: number;
  pageSize: number;
  keywords: string;
}

// Chunk列表Hook返回值接口
export interface UseChunkListReturn extends UseChunkListState {
  fetchChunks: (params?: IFetchChunkListRequestBody) => Promise<void>;
  setKeywords: (keywords: string) => void;
  setCurrentPage: (page: number) => void;
  setPageSize: (size: number) => void;
  refresh: () => Promise<void>;
}

/**
 * Chunk列表数据管理Hook
 * 支持关键词搜索、分页等功能
 */
export const useChunkList = (
  docId: string,
  initialParams?: IFetchChunkListRequestBody
): UseChunkListReturn => {
  const [chunks, setChunks] = useState<IChunk[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(initialParams?.page || 1);
  const [pageSize, setPageSize] = useState(initialParams?.size || 10);
  const [keywords, setKeywords] = useState(initialParams?.keywords || '');

  /**
   * 获取chunk列表
   */
  const fetchChunks = useCallback(async (params?: IFetchChunkListRequestBody) => {
    if (!docId) return;

    try {
      setLoading(true);
      setError(null);

      // 合并参数
      const queryParams = {
        doc_id: docId,
        keywords: params?.keywords ?? keywords,
        page: params?.page ?? currentPage,
        size: params?.size ?? pageSize,
      };

      const response = await knowledgeService.getChunkList(queryParams);

      // 检查响应状态
      if (response.data.code === 0) {
        const data: IChunkListResult = response.data.data;
        setChunks(data.chunks || []);
        setTotal(data.total || 0);
      } else {
        throw new Error(response.data.message || '获取chunk列表失败');
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || '获取chunk列表失败';
      setError(errorMessage);
      console.error('Failed to fetch chunks:', err);
    } finally {
      setLoading(false);
    }
  }, [docId, keywords, currentPage, pageSize]);

  /**
   * 刷新数据
   */
  const refresh = useCallback(async () => {
    await fetchChunks();
  }, [fetchChunks]);

  // 初始化加载数据
  useEffect(() => {
    if (docId) {
      fetchChunks();
    }
  }, [docId, fetchChunks]);

  return {
    chunks,
    total,
    loading,
    error,
    currentPage,
    pageSize,
    keywords,
    fetchChunks,
    setKeywords,
    setCurrentPage,
    setPageSize,
    refresh,
  };
};