import { useState, useEffect, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import knowledgeService from '@/services/knowledge_service';
import type { IKnowledge, IKnowledgeGraph, IKnowledgeResult, IOverviewTital, IFileLogList } from '@/interfaces/database/knowledge';
import type { IFetchKnowledgeListRequestBody, IFetchKnowledgeListRequestParams } from '@/interfaces/request/knowledge';
import logger from '@/utils/logger';

/**
{
    "avatar": "data:image/png;base64,iVBORw0K
    "chunk_num": 1180,
    "create_time": 1759986452748,
    "description": "  213213",
    "doc_num": 16,
    "embd_id": "",
    "id": "dcc2871aa4cd11f08d4116ac85b1de0a",
    "language": "English",
    "name": "k1123",
    "pagerank": 0,
    "parser_config": {
        "auto_keywords": 0,
        "auto_questions": 0,
        "chunk_token_num": 512,
        "delimiter": "\n",
        "graphrag": {
            "entity_types": [
                "organization",
                "person",
                "geo",
                "event",
                "category"
            ],
            "method": "light",
            "use_graphrag": true
        },
        "html4excel": false,
        "layout_recognize": "Plain Text",
        "raptor": {
            "max_cluster": 64,
            "max_token": 256,
            "prompt": "\u8bf7\u603b\u7ed3\u4ee5\u4e0b\u6bb5\u843d\u3002 \u5c0f\u5fc3\u6570\u5b57\uff0c\u4e0d\u8981\u7f16\u9020\u3002 \u6bb5\u843d\u5982\u4e0b\uff1a\n      {cluster_content}\n\u4ee5\u4e0a\u5c31\u662f\u4f60\u9700\u8981\u603b\u7ed3\u7684\u5185\u5bb9\u3002",
            "random_seed": 0,
            "threshold": 0.1,
            "use_raptor": false
        },
        "topn_tags": 3
    },
    "parser_id": "naive",
    "permission": "team",
    "size": 56819092,
    "token_num": 293067,
    "update_time": 1760436169574
}
 */

// 知识库列表Hook状态接口
export interface UseKnowledgeListState {
  knowledgeBases: IKnowledge[];
  total: number;
  loading: boolean;
  error: string | null;
  currentPage: number;
  pageSize: number;
  keywords: string;
}

// 知识库列表Hook返回值接口
export interface UseKnowledgeListReturn extends UseKnowledgeListState {
  fetchKnowledgeBases: (params?: IFetchKnowledgeListRequestParams & IFetchKnowledgeListRequestBody) => Promise<void>;
  setKeywords: (keywords: string) => void;
  setTeamFilter: (teamFilter: string[]) => void;
  setCurrentPage: (page: number) => void;
  setPageSize: (size: number) => void;
  refresh: () => Promise<void>;
}

/**
 * 知识库列表数据管理Hook
 * 支持关键词搜索、分页等功能
 */
export const useKnowledgeList = (
  initialParams?: IFetchKnowledgeListRequestParams & IFetchKnowledgeListRequestBody
): UseKnowledgeListReturn => {
  const { t } = useTranslation();
  const [knowledgeBases, setKnowledgeBases] = useState<IKnowledge[]>([]);
  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?.page_size || 10);
  const [keywords, setKeywords] = useState(initialParams?.keywords || '');
  const [filterData, setFilterData] = useState<any>({});

  /**
   * 获取知识库列表
   */
  const fetchKnowledgeBases = useCallback(async (params?: IFetchKnowledgeListRequestParams & IFetchKnowledgeListRequestBody) => {
    try {
      setLoading(true);
      setError(null);

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

      // 构建请求体
      const requestBody: IFetchKnowledgeListRequestBody = {};
      if (params?.owner_ids && params.owner_ids.length > 0) {
        requestBody.owner_ids = params.owner_ids;
      }

      if (filterData.owner_ids && filterData.owner_ids.length > 0) {
        requestBody.owner_ids = filterData.owner_ids;
      }

      // 构建查询参数
      const requestParams: IFetchKnowledgeListRequestParams = {};
      if (queryParams.page) {
        requestParams.page = queryParams.page;
      }
      if (queryParams.page_size) {
        requestParams.page_size = queryParams.page_size;
      }
      if (queryParams.keywords) {
        requestParams.keywords = queryParams.keywords;
      }

      const response = await knowledgeService.getKnowledgeList(
        Object.keys(requestParams).length > 0 ? requestParams : undefined,
        Object.keys(requestBody).length > 0 ? requestBody : undefined
      );

      // 检查响应状态
      if (response.data.code === 0) {
        const data = response.data.data as IKnowledgeResult;
        setKnowledgeBases(data.kbs || []);
        setTotal(data.total || 0);
      } else {
        throw new Error(response.data.message || t('knowledgeHooks.fetchKnowledgeListFailed'));
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || t('knowledgeHooks.fetchKnowledgeListFailed');
      setError(errorMessage);
      console.error('Failed to fetch knowledge bases:', err);
    } finally {
      setLoading(false);
    }
  }, [keywords, currentPage, pageSize, filterData]);

  /**
   * 刷新当前页面数据
   */
  const refresh = useCallback(() => {
    return fetchKnowledgeBases();
  }, [fetchKnowledgeBases]);

  /**
   * 设置关键词并重置到第一页
   */
  const handleSetKeywords = useCallback((newKeywords: string) => {
    setKeywords(newKeywords);
    setCurrentPage(1);
  }, []);

  const handleSetTeamFilter = useCallback((newTeamFilter: string[]) => {
    setFilterData({ ...filterData, owner_ids: newTeamFilter });
  }, []);

  /**
   * 设置当前页
   */
  const handleSetCurrentPage = useCallback((page: number) => {
    setCurrentPage(page);
  }, []);

  /**
   * 设置页面大小并重置到第一页
   */
  const handleSetPageSize = useCallback((size: number) => {
    setPageSize(size);
    setCurrentPage(1);
  }, []);

  // 当关键词、页码或页面大小变化时重新获取数据
  useEffect(() => {
    logger.info('useEffect currentPage:', currentPage);
    logger.info('useEffect pageSize:', pageSize);
    fetchKnowledgeBases();
  }, [currentPage, pageSize, filterData, keywords]);

  return {
    knowledgeBases,
    total,
    loading,
    error,
    currentPage,
    pageSize,
    keywords,
    fetchKnowledgeBases,
    setKeywords: handleSetKeywords,
    setTeamFilter: handleSetTeamFilter,
    setCurrentPage: handleSetCurrentPage,
    setPageSize: handleSetPageSize,
    refresh,
  };
};

/**
 * 知识库详情Hook
 */
export const useKnowledgeDetail = (kbId: string) => {
  const { t } = useTranslation();
  const [knowledge, setKnowledge] = useState<IKnowledge | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [knowledgeGraph, setKnowledgeGraph] = useState<IKnowledgeGraph | null>(null);

  const showKnowledgeGraph = useMemo(() => {
    return knowledgeGraph !== null && Object.keys(knowledgeGraph?.graph || {}).length > 0;
  }, [knowledgeGraph]);

  const fetchKnowledgeDetail = useCallback(async () => {
    if (!kbId) return;

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

      const response = await knowledgeService.getKnowledgeDetail({ kb_id: kbId });

      if (response.data.code === 0) {
        setKnowledge(response.data.data);
      } else {
        throw new Error(response.data.message || t('knowledgeHooks.fetchKnowledgeDetailFailed'));
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || t('knowledgeHooks.fetchKnowledgeDetailFailed');
      setError(errorMessage);
      console.error('Failed to fetch knowledge detail:', err);
    } finally {
      setLoading(false);
    }
  }, [kbId]);

  const fetchKnowledgeGraph = useCallback(async () => {
    if (!kbId) return;

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

      const response = await knowledgeService.getKnowledgeGraph(kbId);

      if (response.data.code === 0) {
        setKnowledgeGraph(response.data.data);
      } else {
        throw new Error(response.data.message || t('knowledgeHooks.fetchKnowledgeGraphFailed'));
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || t('knowledgeHooks.fetchKnowledgeGraphFailed');
      setError(errorMessage);
      console.error('Failed to fetch knowledge graph:', err);
    } finally {
      setLoading(false);
    }
  }, [kbId]);

  useEffect(() => {
    fetchKnowledgeDetail();
    fetchKnowledgeGraph();
  }, [fetchKnowledgeDetail, fetchKnowledgeGraph]);

  return {
    knowledge,
    knowledgeGraph,
    loading,
    error,
    refresh: fetchKnowledgeDetail,
    showKnowledgeGraph,
  };
};

/**
 * 知识库操作Hook
 * 提供创建、更新、删除知识库的功能
 */
export const useKnowledgeOperations = () => {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  /**
   * 创建知识库
   */
  const createKnowledge = useCallback(async (data: Partial<IKnowledge>) => {
    try {
      setLoading(true);
      setError(null);

      const response = await knowledgeService.createKnowledge(data);

      if (response.data.code === 0) {
        return response.data.data;
      } else {
        throw new Error(response.data.message || t('knowledgeHooks.createKnowledgeFailed'));
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || t('knowledgeHooks.createKnowledgeFailed');
      setError(errorMessage);
      console.error('Failed to create knowledge:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 更新知识库基础信息
   * 包括名称、描述、语言等基本信息
   */
  const updateKnowledgeBasicInfo = useCallback(async (data: {
    kb_id: string;
  } & Partial<IKnowledge>) => {
    try {
      setLoading(true);
      setError(null);

      const response = await knowledgeService.updateKnowledge(data);

      if (response.data.code === 0) {
        return response.data.data;
      } else {
        throw new Error(response.data.message || t('knowledgeHooks.updateKnowledgeBasicInfoFailed'));
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || t('knowledgeHooks.updateKnowledgeBasicInfoFailed');
      setError(errorMessage);
      console.error('Failed to update knowledge basic info:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 更新知识库模型配置
   * 包括嵌入模型、解析器配置、相似度阈值等
   */
  const updateKnowledgeModelConfig = useCallback(async (data: {
    kb_id: string;
  } & Partial<IKnowledge>) => {
    try {
      setLoading(true);
      setError(null);

      const updateData = {
        ...data,
      };

      const response = await knowledgeService.updateKnowledge(updateData);

      if (response.data.code === 0) {
        return response.data.data;
      } else {
        throw new Error(response.data.message || t('knowledgeHooks.updateKnowledgeModelConfigFailed'));
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || t('knowledgeHooks.updateKnowledgeModelConfigFailed');
      setError(errorMessage);
      console.error('Failed to update knowledge model config:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 删除知识库
   */
  const deleteKnowledge = useCallback(async (kbId: string) => {
    try {
      setLoading(true);
      setError(null);

      const response = await knowledgeService.removeKnowledge({ kb_id: kbId });

      if (response.data.code === 0) {
        return response.data.data;
      } else {
        throw new Error(response.data.message || t('knowledgeHooks.deleteKnowledgeFailed'));
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || t('knowledgeHooks.deleteKnowledgeFailed');
      setError(errorMessage);
      console.error('Failed to delete knowledge:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 清除错误状态
   */
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  return {
    loading,
    error,
    createKnowledge,
    updateKnowledgeBasicInfo,
    updateKnowledgeModelConfig,
    deleteKnowledge,
    clearError,
  };
};

/**
 * 知识库批量操作Hook
 * 提供批量删除等功能
 */
export const useKnowledgeBatchOperations = () => {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  /**
   * 批量删除知识库
   */
  const batchDeleteKnowledge = useCallback(async (kbIds: string[]) => {
    try {
      setLoading(true);
      setError(null);

      const results = await Promise.allSettled(
        kbIds.map(kbId => knowledgeService.removeKnowledge({ kb_id: kbId }))
      );

      const failures = results
        .map((result, index) => ({ result, index }))
        .filter(({ result }) => result.status === 'rejected')
        .map(({ index }) => kbIds[index]);

      if (failures.length > 0) {
        throw new Error(`${t('knowledgeHooks.batchDeleteFailedKnowledgeBases')}: ${failures.join(', ')}`);
      }

      return results;
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || t('knowledgeHooks.batchDeleteKnowledgeFailed');
      setError(errorMessage);
      console.error('Failed to batch delete knowledge:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 清除错误状态
   */
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  return {
    loading,
    error,
    batchDeleteKnowledge,
    clearError,
  };
};



/* ============================================================================
 * useKnowledgeOverview
 * ============================================================================ */

const LOGS_TABS = {
  FILE_LOGS: 'fileLogs',
  DATASET_LOGS: 'datasetLogs',
} as const

type LogTabs = typeof LOGS_TABS[keyof typeof LOGS_TABS]

/**
 * 知识库详情页 - 概览数据获取Hook
 */
export interface UseKnowledgeOverviewReturn {
  overview: IOverviewTital | null;
  fileLogs: IFileLogList | null;
  datasetLogs: IFileLogList | null;
  loading: boolean;
  error: string | null;
  currentPage: number;
  pageSize: number;
  activeTab: LogTabs;
  keywords: string;
  setCurrentPage: (page: number) => void;
  setPageSize: (size: number) => void;
  setActiveTab: (tab: LogTabs) => void;
  setKeywords: (keywords: string) => void;
  refresh: () => Promise<void>;
}

export const useKnowledgeOverview = (kb_id: string): UseKnowledgeOverviewReturn => {
  const { t } = useTranslation();
  const [overview, setOverview] = useState<IOverviewTital | null>(null);
  const [fileLogs, setFileLogs] = useState<IFileLogList | null>(null);
  const [datasetLogs, setDatasetLogs] = useState<IFileLogList | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [activeTab, setActiveTab] = useState<LogTabs>(LOGS_TABS.FILE_LOGS);
  const [keywords, setKeywordsState] = useState('');

  const fetchOverviewTital = useCallback(async () => {
    if (!kb_id) return;
    try {
      setLoading(true);
      setError(null);
      const response = await knowledgeService.getKnowledgeBasicInfo({ kb_id });
      if (response.data.code === 0) {
        setOverview(response.data.data);
      } else {
        throw new Error(response.data.message || t('knowledgeHooks.fetchOverviewFailed'));
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message || t('knowledgeHooks.fetchOverviewFailed');
      setError(errorMessage);
      console.error('Failed to fetch overview tital:', err);
    } finally {
      setLoading(false);
    }
  }, [kb_id]);

  const fetchPipelineLogs = useCallback(async () => {
    if (!kb_id) return;
    try {
      setLoading(true);
      setError(null);
      const response = await knowledgeService.getDataPipelineLogs({
        kb_id,
        page: currentPage,
        page_size: pageSize,
        keywords,
      });
      if (response.data.code === 0) {
        setFileLogs(response.data.data as IFileLogList);
      } else {
        throw new Error(response.data.message);
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message;
      setError(errorMessage);
      console.error('Failed to fetch data pipeline logs:', err);
    } finally {
      setLoading(false);
    }
  }, [kb_id, currentPage, pageSize, keywords]);

  const fetchPipelineDatasetLogs = useCallback(async () => {
    if (!kb_id) return;
    try {
      setLoading(true);
      setError(null);
      const response = await knowledgeService.getPipelineDatasetLogs({
        kb_id,
        page: currentPage,
        page_size: pageSize,
        keywords,
      });
      if (response.data.code === 0) {
        setDatasetLogs(response.data.data as IFileLogList);
      } else {
        throw new Error(response.data.message);
      }
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || err.message;
      setError(errorMessage);
      console.error('Failed to fetch pipeline dataset logs:', err);
    } finally {
      setLoading(false);
    }
  }, [kb_id, currentPage, pageSize, keywords]);

  useEffect(() => {
    fetchOverviewTital();
  }, [fetchOverviewTital]);

useEffect(() => {
  if (activeTab === LOGS_TABS.FILE_LOGS) {
    fetchPipelineLogs();
  } else {
    fetchPipelineDatasetLogs();
  }
}, [activeTab, fetchPipelineLogs, fetchPipelineDatasetLogs]);

// 设置关键词并重置到第一页
const setKeywords = useCallback((kw: string) => {
  setKeywordsState(kw);
  setCurrentPage(1);
}, []);

  const refresh = useCallback(async () => {
    await Promise.all([
      fetchOverviewTital(),
      fetchPipelineLogs(),
      fetchPipelineDatasetLogs(),
    ]);
  }, [fetchOverviewTital, fetchPipelineLogs, fetchPipelineDatasetLogs]);

  return {
    overview,
    fileLogs,
    datasetLogs,
    loading,
    error,
    currentPage,
    pageSize,
    activeTab,
    keywords,
    setCurrentPage,
    setPageSize,
    setActiveTab,
    setKeywords,
    refresh,
  };
};