import { useEffect, useState } from "react";
import { requestTextToChat } from "@/service/chat";
import { useTextChat } from "@/store/textChatStore";
import { TAgentDetail } from "@/types/agent";
import { delay, getLoginId, isSuccess } from "@/utils";
import { useAudioStreamPlayer } from "@/utils/audioStreamPlayer";

import { EChatRole, EContentType, TAnyMessage } from "@/types/bot";

import { usePostMessage, saveAgentChatContentToServer, sendMyMessageToServer } from "./useMessage";

import { getRecommendPrompt } from "@/service/chat";

interface Props {
  agent: TAgentDetail | null;
  historyList: TAnyMessage[];
  enableOutputAudioStream: boolean;
  setShowWelcome?: (b: boolean) => void;
  setIsVoice?: (b: boolean) => void;
  setDisabled?: (b: boolean) => void;
}

let stopChunk: (() => void) | undefined;
export const useChatInput = ({
  agent,
  enableOutputAudioStream,
  setShowWelcome,
  setDisabled,
  historyList,
}: Props) => {
  let myMsgUk = "";
  let mySessionId = "";
  
  // 聊天框 store
  const {
    pushRobotMessage,
    updateRobotMessage,
    getCurrentRobotMessage,
    pushMessage,
    updateMessage,
    deleteMessage,
    setQuestions,
    questions,
    messageStopHandle,
    setMessageStopHandle,
    setReacting,
    setScrollTop,
    setAutoScroll,
  } = useTextChat();
  
  

  // 聊天框内消息定时上报
  const { startTimedMessage, stopTimedMessage } =
    usePostMessage(getCurrentRobotMessage);

  // 聊天消息流式音频播报
  const {isLastChunk, initPlay, setFistChunk, pushBase64ToQuene, playChunk, stopPlayChunk, stopPlay, onPlayerStatusChanged, setIsLastChunk } =
    useAudioStreamPlayer();

  const clearActions = ()=> {
    stopChunk?.();
    stopTimedMessage();
    stopPlayChunk();
    setMessageStopHandle(null)
    setReacting(false)
    setDisabled?.(false);
  }

  const enableUserInput = ()=> {
    setReacting(false)
    setMessageStopHandle(null)
  }

  
  // 聊天
  const chatWithGpt = async (
    message: string,
    sessionId: string,
    msgUk: string
  ) => {
    
    if (!agent?.agentId) {
      return;
    }
    const loginId = getLoginId();
    if (!loginId) {
      return;
    }

    if(messageStopHandle){
      messageStopHandle()
    }
    setShowWelcome?.(false);
    setQuestions([]);
    initPlay();
    setReacting(true)

    let currentRobotMsgUk = "";
    await delay(300);
    setDisabled?.(true);
    
    const submitMyMessageSuccess = await sendMyMessageToServer({
      agentId: agent.agentId,
      message,
      loginId,
      msgUk,
      sessionId
    })
    
    // todo: 如果自己发送的消息失败了，需要显示错误信息提示用户？
    if (!submitMyMessageSuccess) {
      setReacting(false)
      setDisabled?.(false);
      return;
    }
    
    

    let isFirstChunk = true;
    console.log('==== start new chat ====')
    // 取最后两条消息带上
    // const allMessages = [...historyList.reverse(), ...list];
    // const prevMessages = allMessages
    // .slice(Math.max(0, allMessages.length - 2)) // 确保不会负数
    // .map(item => ({
    //   content: item.content as string,
    //   contentType: item.contentType ?? EContentType.TextPlain,
    //   role: item.role,
    // }));
    // 发起文本聊天
    const request = requestTextToChat({
      params: {
        agentId: agent.agentId,
        isEnableOutputAudioStream: enableOutputAudioStream,
        isEnableSearch: false,
        isEnableThinking: false,
        loginId,
        messages: [
        {
          content: message,
          contentType: EContentType.TextPlain,
          role: EChatRole.User,
        }],
        sessionId,
      },
      onStart: () => {

        setMessageStopHandle(()=> {
          const currentRobotMessage = getCurrentRobotMessage();
          if(currentRobotMessage?.content.length === 0){
            deleteMessage(currentRobotMessage.msgUk);
          }
          clearActions()
          console.log('按下停止接收键')
        })

        // 推一个空回复，用于展示 ui
        const blankMessage = {
          role: EChatRole.Assistant,
          contentType: EContentType.TextPlain,
          saveStatus: 0,
          content: "",
          reasoningContent: "",
          isStreaming: false,
          msgUk: currentRobotMsgUk,
          dislikeReason: "",
          robot: {
            avatar: agent?.avatarUrl ?? "",
            name: agent?.name ?? "",
            agentId: agent?.agentId ?? "",
          },
        };
        currentRobotMsgUk = pushRobotMessage(blankMessage);
        // 先暂停
        stopTimedMessage();
        // 开始定时发送，每5秒发送一次
        startTimedMessage(
          {
            loginId,
            messages: [
              {
                ...blankMessage,
              },
            ],
            agentId: agent.agentId ?? "",
            sessionId,
          },
          5000
        );

        isFirstChunk = true;
      },
      // 音频输出单独处理
      onAudioParsed: (m) => {
        const audioStr = m?.body?.content?.audio ?? ''
        // if(!audioStr.length){
        //   return;
        // }
        if (isFirstChunk) {
          isFirstChunk = false;
          setFistChunk(audioStr, request.reqTask);
        } else {
          pushBase64ToQuene(audioStr);
        }
        playChunk();
      },
      onReceived: (m) => {
        updateRobotMessage(m.content ?? '', m.body ?? {});
      },
      // 流式结束
      onFinished: async (m) => {
        const currentRobotMessage = getCurrentRobotMessage();
        console.log(
          "回复完毕 ok, 当前robotmessage: ",
          currentRobotMessage,
          m?.body?.content
        );
        // 标记 chunk 已接收完毕
        setIsLastChunk()
        // 如果是非声音朗读，则需要隐藏 停止按钮
        if(!enableOutputAudioStream){
          enableUserInput()
        }
        
        stopTimedMessage();
        if (!agent.agentId) {
          return;
        }
        setDisabled?.(false);
        // 如果没有任何回答，则显示
        if (!currentRobotMessage?.content?.length) {
          updateRobotMessage("服务器繁忙...");
          return;
        }

        // 将智能体的回答保存至服务器
        // currentRobotMessage.content 保存的是当前完整的智能体回复信息文本
        const content = currentRobotMessage.content as string;
        updateRobotMessage(content, currentRobotMessage?.body, 2, true);

        // 获取相关提示问题
        const response = await getRecommendPrompt({
          agentId: agent.agentId,
          sessionId,
        });
        // todo: 如果用户快速输入需要将前面的问题答案丢弃，根据 currentRobotMessage.msgUk 来设置 questions
        if (isSuccess(response.status)) {
          setQuestions(response.data.questions);
        }
      },
      // 此处表示发起的请求已结束，但流式可能还在继续
      onComplete: async () => {
        // 为防止服务端没有终止消息，当接口请求结束时强制再保存一次消息体，以防定时保存的消息体漏掉最后一部分
        const currentRobotMessage = getCurrentRobotMessage();
        console.log("--------- onComplete", agent.agentId, currentRobotMessage?.robot?.agentId );
        if (agent.agentId && (currentRobotMessage?.robot?.agentId  === agent.agentId)) {
          console.log("回复 onComplete", agent, currentRobotMessage );
          stopTimedMessage();
          setDisabled?.(false);
          isFirstChunk = true;
          saveAgentChatContentToServer(
            currentRobotMessage,
            loginId,
            agent.agentId,
            sessionId
          );
        }
        
      },
      onError: () => {
        setDisabled?.(false);
        setReacting(false)
        currentRobotMsgUk && deleteMessage(currentRobotMsgUk);
      },
    });

    stopChunk = request.stopChunk
  };
  // 聊天录制语音转文本后发送
  const sendVoiceChatMessage = (message: string) => {
    // 如果主意录制无法识别文本，则去掉空气泡框
    if(!message.length){
      console.log('empty message')
      myMsgUk && deleteMessage(myMsgUk);
      return 
    }
    updateMessage(message, myMsgUk);
    chatWithGpt(message, mySessionId, myMsgUk);
  };
  // 聊天文本发送
  const sendChatMessage = async (message: string) => {
    const { sessionId, msgUk } = pushMessage(message);
    chatWithGpt(message, sessionId, msgUk);
  };

  // 推一个自己的空气泡框
  const handleBeforeSend = () => {
    console.log('bubble started')
    const { sessionId, msgUk } = pushMessage("");
    console.log('bubble end')
    myMsgUk = msgUk;
    mySessionId = sessionId;
  };

  // 发生识别错误时，删除当前自己发出的气泡框
  const handleVoiceError = () => {
    console.log('handleVoiceError: ', myMsgUk)
    deleteMessage(myMsgUk);
  };

  // 由于要等播放完毕后才能隐藏“停止按钮”，
  // 等待音频播放完毕才能更改状态
  onPlayerStatusChanged((status)=> {
    console.log('播放器播放状态====', status)
    if(status === 'stop'){
      enableUserInput()
    }
  })
  // 如果停止语音输出，则停止播放
  useEffect(() => {
    if (!enableOutputAudioStream) {
      stopPlay();
      // 如果刚好是最后的 chunk 了则需要立即隐藏 '停止按钮'
      if(isLastChunk){
        enableUserInput()
      }
    }
  }, [enableOutputAudioStream]);
  
  // 清理
  useEffect(() => {
    console.log('chat input ')
    return () => {
      clearActions();
      setAutoScroll(true);
      setScrollTop(0);
      console.log('clear chat')
    };
  }, []);

  return {
    setQuestions,
    sendVoiceChatMessage,
    sendChatMessage,
    questions,
    handleBeforeSend,
    handleVoiceError,
  };
};
