import { useCallback, useEffect, useState } from "react";
import { Image, Toast } from "antd-mobile";
import MessageCom from "./component/message";
import VoiceRecord from "./component/voice";
import { XPopup, type FloatMenuItemConfig } from "@workspace/shared";
import type { Message } from "../types";
import { useGetDialog } from "@/api/getDialog";
import { useUploadAudio } from "@/api/translate";

import dogSvg from "@/assets/translate/dog.svg";
import catSvg from "@/assets/translate/cat.svg";
import pigSvg from "@/assets/translate/pig.svg";
import { MoreTwo } from "@icon-park/react";
import SearchCom from "./component/search";
interface DefinedProps {
  searchVisible: boolean;
}

const menuItems: FloatMenuItemConfig[] = [
  { icon: <Image src={dogSvg} />, type: "dog" },
  { icon: <Image src={catSvg} />, type: "cat" },
  { icon: <Image src={pigSvg} />, type: "pig" },
  {
    icon: <MoreTwo theme="outline" size="24" fill="#666" strokeWidth={3} strokeLinecap="butt" />,
    type: "add",
  },
];
function Index(props: DefinedProps) {
  const { searchVisible } = props;
  const { loading: _uploadLoading, error: _uploadError, getDialog } = useGetDialog();
  const { loading: _audioLoading, error: _audioError, uploadAudio } = useUploadAudio();
  const [messages, setMessages] = useState<Message[]>([]);
  const [isRecording, setIsRecording] = useState(false); //是否录音中
  const [_currentLanguage, setCurrentLanguage] = useState<FloatMenuItemConfig>();
  const [visible, setVisible] = useState<boolean>(false);
  const [dialogId, setDialogId] = useState<number>(0);

  useEffect(() => {
    setCurrentLanguage(menuItems[0]);
    fetchInitialMessages();
  }, []);

  // 滚动到底部
  const scrollToBottom = useCallback(() => {
    const container = document.querySelector(".message");

    if (container) {
      container.scrollTop = container.scrollHeight;
      console.log("container", container.scrollHeight);
    }
  }, []);

  // 添加初始化数据的逻辑
  const fetchInitialMessages = async () => {
    try {
      // 这里替换为实际的API调用
      // const response = await fetch('/api/messages');
      const response = await getDialog();
      const initialMessages: Message[] = response.data?.data?.messages || [];

      setDialogId(response.data?.data?.dialogId);
      setMessages(initialMessages);
    } catch (error) {
      console.error("获取初始化数据失败:", error);
      Toast.show("获取消息失败");
      // 失败时设置为空数组
      setMessages([]);
    }
  };

  // 监听消息变化，自动滚动到底部
  useEffect(() => {
    if (messages.length > 0) {
      requestAnimationFrame(() => {
        scrollToBottom();
      });
    }
  }, [messages, scrollToBottom]);

  //完成录音
  const onRecordingComplete = useCallback(
    (audioUrl: string, actualDuration: number, formData: FormData) => {
      console.log(audioUrl, "audioUrl");
      const newMessage: Message = {
        id: Date.now(),
        contentText: audioUrl,
        contentDuration: actualDuration,
        isTranslating: true,
      };

      setMessages((prev) => [...prev, newMessage]);
      setTimeout(() => {
        onTranslateAudio(formData, newMessage.id);
      }, 500);

      Toast.show("语音已发送");
    },
    [messages]
  );

  //翻译
  const onTranslateAudio = useCallback(
    async (formData: FormData, id: number) => {
      try {
        const response = await uploadAudio(formData);
        const translatedData = response.data;

        if (translatedData.data.transStatus) {
          setMessages((prev) =>
            prev.map((msg) =>
              msg.id === id
                ? {
                    ...msg,
                    ...translatedData.data,
                    isTranslating: false,
                    isRefresh: false,
                  }
                : msg
            )
          );
        } else {
          setMessages((prev) =>
            prev.map((msg) =>
              msg.id === id
                ? {
                    ...msg,
                    id: translatedData.data.id,
                    petName: "未知宠物",
                    transStatus: translatedData.data.transStatus,
                    createTime: translatedData.data.createTime,
                    isTranslating: false,
                    isRefresh: false,
                  }
                : msg
            )
          );
        }
      } catch (error) {
        console.error("翻译失败:", error);
        Toast.show("翻译失败，请重试");

        setMessages((prev) =>
          prev.map((msg) =>
            msg.id === id
              ? {
                  ...msg,
                  isTranslating: false,
                  isRefresh: false,
                  translatedText: "翻译失败，请重试",
                }
              : msg
          )
        );
      }
    },
    [messages]
  );

  const refreshMessages = (formData: FormData, messageId: number) => {
    setMessages((prev) =>
      prev.map((msg) =>
        msg.id === messageId
          ? {
              ...msg,
              isTranslating: true,
              isRefresh: true,
            }
          : msg
      )
    );
    onTranslateAudio(formData, messageId);
  };

  const onSetIsRecording = (flag: boolean) => {
    setIsRecording(flag);
  };

  // const onLanguage = (item: FloatMenuItemConfig) => {
  //   if (item.type === "add") {
  //     setVisible(true);
  //   } else {
  //     setCurrentLanguage(item);
  //   }
  // };

  return (
    <div className="translate-container">
      {searchVisible && (
        <div className="header">
          <SearchCom handleAllAni={() => {}} />
        </div>
      )}

      {/* <div onClick={() => scrollToBottom()}>111</div> */}

      <MessageCom
        data={messages}
        isRecording={isRecording}
        onRefresh={refreshMessages}
      ></MessageCom>

      {/* <div
        className="message-container"
        style={{
          flex: 1,
          overflowY: "auto",
          minHeight: 0,
          display: "flex",
          flexDirection: "column",
        }}
      >
        <MessageCom
          data={messages}
          isRecording={isRecording}
          onRefresh={refreshMessages}
        ></MessageCom>
        <div ref={messagesEndRef} style={{ float: "left", clear: "both", height: "1px" }} />
      </div> */}

      {/* <div className="he" ref={messagesEndRef} /> */}

      <VoiceRecord
        dialogId={dialogId}
        onRecordingComplete={onRecordingComplete}
        isRecording={isRecording}
        onSetIsRecording={onSetIsRecording}
      />
      {/* <FloatingMenu menuItems={menuItems} value={currentLanguage} onChange={onLanguage} /> */}
      <XPopup
        title="选择翻译语种"
        visible={visible}
        onClose={() => {
          setVisible(false);
        }}
      >
        <div className="card">
          <span>快捷选项</span>
          <div></div>
        </div>
        <div className="card">
          <span>宠物语种</span>
        </div>
      </XPopup>
    </div>
  );
}

export default Index;
