import { MessageStatus } from "@openim/wasm-client-sdk";
import { MessageItem, WsResponse } from "@openim/wasm-client-sdk/lib/types/entity";
import { SendMsgParams } from "@openim/wasm-client-sdk/lib/types/params";
import { useCallback } from "react";

import { IMSDK } from "@/layout/MainContentWrap";
import { useConversationStore } from "@/store";
import { feedbackToast } from "@/utils/common";
import { emit } from "@/utils/events";

import { pushNewMessage, updateOneMessage } from "../useHistoryMessageList";

export type SendMessageParams = Partial<Omit<SendMsgParams, "message">> & {
  message: MessageItem;
  needPush?: boolean;
};

const sendErrorTips = [
  { code: 1303, tip: "对方还不是你的同事，请先添加对方" },
  { code: 1302, tip: "对方已把你加入黑名单，无法发送" },
  { code: 1101, tip: "对方账号不存在" },
  { code: 1501, tip: "登录已过期，请重新登录" },
  { code: 1502, tip: "登录凭证无效，请重新登录" },
];

/** 把 SDK 原始错误映射成中文提示 */
const mapSendError = (error: unknown): string => {
  const s = String(error ?? "");
  for (const { code, tip } of sendErrorTips) {
    if (s.includes(String(code))) return tip;
  }
  if (/10000|10001|timeout|network|网络/i.test(s)) return "网络异常，请检查网络后重试";
  return "消息没发出去，请重试";
};

export function useSendMessage() {
  const sendMessage = useCallback(
    async ({ recvID, groupID, message, needPush }: SendMessageParams) => {
      const currentConversation = useConversationStore.getState().currentConversation;
      const sourceID = recvID || groupID;
      const inCurrentConversation =
        currentConversation?.userID === sourceID ||
        currentConversation?.groupID === sourceID ||
        !sourceID;
      needPush = needPush ?? inCurrentConversation;

      if (needPush) {
        pushNewMessage(message);
        emit("CHAT_LIST_SCROLL_TO_BOTTOM");
      }

      const finalRecvID = recvID ?? currentConversation?.userID ?? "";
      const finalGroupID = groupID ?? currentConversation?.groupID ?? "";
      // 单聊且接收方为空：会话对象异常，明确提示而不是静默失败
      if (!finalGroupID && !finalRecvID) {
        updateOneMessage({ ...message, status: MessageStatus.Failed });
        feedbackToast({ msg: "请先添加对方为同事，再发起会话" });
        return;
      }

      const options = {
        recvID: finalRecvID,
        groupID: finalGroupID,
        message,
      };

      try {
        const { data: successMessage } = await IMSDK.sendMessage(options);
        updateOneMessage(successMessage);
      } catch (error) {
        updateOneMessage({
          ...message,
          status: MessageStatus.Failed,
        });
        feedbackToast({ error, msg: mapSendError(error) });
      }
    },
    [],
  );

  return {
    sendMessage,
  };
}
