import { AgentCategory, AgentQuery } from '@/constants/agent';
import { NavigateToDataflowResultProps } from '@/pages/dataflow-result/interface';
import { Routes } from '@/routes';
import { useCallback } from 'react';
import Bridge from '@teres/iframe-bridge';
import { useNavigate, useParams, useSearchParams } from 'umi';

export enum QueryStringMap {
  KnowledgeId = 'knowledgeId',
  id = 'id',
}

export const useNavigatePage = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { id } = useParams();

  // 统一由 @teres/iframe-bridge 提供嵌入判断与消息封装

  // 统一的跳转封装：嵌入模式下向父页面发送消息，否则使用内部 navigate
  const navigateOrPost = useCallback(
    (to: string, options?: { hostAgents?: boolean }) => {
      console.log('Bridge: ', Bridge);
      console.log('Bridge.isEmbedded', Bridge.isEmbedded());
      if (Bridge.isEmbedded()) {
        if (options?.hostAgents) {
          // 返回到宿主应用的 /agents
          if (typeof Bridge.clientClose === 'function') {
            Bridge.clientClose();
          } else {
            Bridge.clientNavigate(Bridge.toHostPath(Routes.Agents));
          }
          return;
        }
        Bridge.clientNavigate(Bridge.toHostPath(to));
        return;
      }
      navigate(to);
    },
    [navigate],
  );

  const navigateToDatasetList = useCallback(() => {
    navigateOrPost(Routes.Datasets);
  }, [navigateOrPost]);

  const navigateToDataset = useCallback(
    (id: string) => () => {
      // navigate(`${Routes.DatasetBase}${Routes.DataSetOverview}/${id}`);
      navigateOrPost(`${Routes.Dataset}/${id}`);
    },
    [navigateOrPost],
  );
  const navigateToDatasetOverview = useCallback(
    (id: string) => () => {
      navigateOrPost(`${Routes.DatasetBase}${Routes.DataSetOverview}/${id}`);
    },
    [navigateOrPost],
  );

  const navigateToDataFile = useCallback(
    (id: string) => () => {
      navigateOrPost(`${Routes.DatasetBase}${Routes.DatasetBase}/${id}`);
    },
    [navigateOrPost],
  );

  const navigateToHome = useCallback(() => {
    navigateOrPost(Routes.Root);
  }, [navigateOrPost]);

  const navigateToProfile = useCallback(() => {
    navigateOrPost(Routes.ProfileSetting);
  }, [navigateOrPost]);

  const navigateToOldProfile = useCallback(() => {
    navigateOrPost(Routes.UserSetting);
  }, [navigateOrPost]);

  const navigateToChatList = useCallback(() => {
    navigateOrPost(Routes.Chats);
  }, [navigateOrPost]);

  const navigateToChat = useCallback(
    (id: string) => () => {
      navigateOrPost(`${Routes.Chat}/${id}`);
    },
    [navigateOrPost],
  );

  const navigateToAgents = useCallback(() => {
    // 嵌入模式下返回宿主应用的 /agents；独立模式跳转 ragflow 内部 /agents
    navigateOrPost(Routes.Agents, { hostAgents: true });
  }, [navigateOrPost]);

  const navigateToAgentList = useCallback(() => {
    navigateOrPost(Routes.AgentList);
  }, [navigateOrPost]);

  const navigateToAgent = useCallback(
    (id: string, category?: AgentCategory) => () => {
      navigateOrPost(`${Routes.Agent}/${id}?${AgentQuery.Category}=${category}`);
    },
    [navigateOrPost],
  );

  const navigateToDataflow = useCallback(
    (id: string) => () => {
      navigateOrPost(`${Routes.DataFlow}/${id}`);
    },
    [navigateOrPost],
  );

  const navigateToAgentLogs = useCallback(
    (id: string) => () => {
      navigateOrPost(`${Routes.AgentLogPage}/${id}`);
    },
    [navigateOrPost],
  );

  const navigateToAgentTemplates = useCallback(() => {
    navigateOrPost(Routes.AgentTemplates);
  }, [navigateOrPost]);

  const navigateToSearchList = useCallback(() => {
    navigateOrPost(Routes.Searches);
  }, [navigateOrPost]);

  const navigateToSearch = useCallback(
    (id: string) => () => {
      navigateOrPost(`${Routes.Search}/${id}`);
    },
    [navigateOrPost],
  );

  const navigateToChunkParsedResult = useCallback(
    (id: string, knowledgeId?: string) => () => {
      navigateOrPost(
        `${Routes.ParsedResult}/chunks?id=${knowledgeId}&doc_id=${id}`,
      );
    },
    [navigateOrPost],
  );

  const getQueryString = useCallback(
    (queryStringKey?: QueryStringMap) => {
      const allQueryString = {
        [QueryStringMap.KnowledgeId]: searchParams.get(
          QueryStringMap.KnowledgeId,
        ),
        [QueryStringMap.id]: searchParams.get(QueryStringMap.id),
      };
      if (queryStringKey) {
        return allQueryString[queryStringKey];
      }
      return allQueryString;
    },
    [searchParams],
  );

  const navigateToChunk = useCallback(
    (route: Routes) => {
      navigateOrPost(
        `${route}/${id}?${QueryStringMap.KnowledgeId}=${getQueryString(QueryStringMap.KnowledgeId)}`,
      );
    },
    [getQueryString, id, navigateOrPost],
  );

  const navigateToFiles = useCallback(
    (folderId?: string) => {
      navigateOrPost(`${Routes.Files}?folderId=${folderId}`);
    },
    [navigateOrPost],
  );

  const navigateToDataflowResult = useCallback(
    (props: NavigateToDataflowResultProps) => () => {
      let params: string[] = [];
      Object.keys(props).forEach((key) => {
        // @ts-ignore
        if (props[key]) {
          // @ts-ignore
          params.push(`${key}=${props[key]}`);
        }
      });
      navigateOrPost(
        // `${Routes.ParsedResult}/${id}?${QueryStringMap.KnowledgeId}=${knowledgeId}`,
        `${Routes.DataflowResult}?${params.join('&')}`,
      );
    },
    [navigateOrPost],
  );

  return {
    navigateToDatasetList,
    navigateToDataset,
    navigateToDatasetOverview,
    navigateToHome,
    navigateToProfile,
    navigateToChatList,
    navigateToChat,
    navigateToChunkParsedResult,
    getQueryString,
    navigateToChunk,
    navigateToAgents,
    navigateToAgent,
    navigateToAgentLogs,
    navigateToAgentTemplates,
    navigateToSearchList,
    navigateToSearch,
    navigateToFiles,
    navigateToAgentList,
    navigateToOldProfile,
    navigateToDataflowResult,
    navigateToDataflow,
    navigateToDataFile,
  };
};
