import { ExclamationCircleFilled, LoadingOutlined } from "@ant-design/icons";
import { MessageStatus } from "@openim/wasm-client-sdk";
import { Spin, Tooltip } from "antd";
import { t } from "i18next";
import { FC, useEffect, useState } from "react";

import { IMSDK } from "@/layout/MainContentWrap";
import { useConversationStore } from "@/store";

import { IMessageItemProps } from ".";
import styles from "./message-item.module.scss";
import { updateOneMessage } from "../useHistoryMessageList";

const MessageSuffix: FC<IMessageItemProps> = ({ message }) => {
  const [showSending, setShowSending] = useState(false);

  useEffect(() => {
    if (message.status !== MessageStatus.Sending) return;
    const timer = setTimeout(() => {
      if (message.status === MessageStatus.Sending) {
        setShowSending(true);
      }
    }, 1000);
    return () => {
      clearTimeout(timer);
    };
  }, [message.status]);

  const resendMessage = async () => {
    const currentConversation = useConversationStore.getState().currentConversation;
    updateOneMessage({ ...message, status: MessageStatus.Sending });
    try {
      const { data: successMessage } = await IMSDK.sendMessage({
        recvID: currentConversation?.userID ?? "",
        groupID: currentConversation?.groupID ?? "",
        message,
      });
      updateOneMessage(successMessage);
    } catch (error) {
      updateOneMessage({ ...message, status: MessageStatus.Failed });
    }
  };

  return (
    <div className={styles.suffix}>
      {showSending && message.status === MessageStatus.Sending && (
        <Spin
          className="flex"
          indicator={<LoadingOutlined style={{ fontSize: 16 }} spin rev={undefined} />}
        />
      )}
      {message.status === MessageStatus.Failed && (
        <Tooltip title={t("messageDescription.resendTip")}>
          <ExclamationCircleFilled
            className="cursor-pointer text-base text-[var(--warn-text)]"
            rev={undefined}
            onClick={resendMessage}
          />
        </Tooltip>
      )}
    </div>
  );
};

export default MessageSuffix;
