import { View, Text, type CommonEvent } from "@tarojs/components"
import IconKeyboard from "@/components/icon/icon-keyboard"
import { useVoiceRecord } from "@/components/voice-recorder";
import { useState } from "react";
import { getChatSession } from "@/store/chat";
import style from './index.module.less'
import { speechToText } from "@/service/bot";
import { isSuccess } from "@/utils";
interface Props {
  disabled: boolean,
  onIconClick: () => void
  onSend: (msg: string)=> void
  beforeSend: ()=> void
  onError: ()=> void
  agentId?: string
}
export default ({agentId,disabled, onIconClick, onSend, beforeSend, onError}:Props) => {
  const [speechStatus, setSpeechStatus] = useState(0);
  const { start, stop, onStop } = useVoiceRecord('wav');
  const onLongPress = (e?: CommonEvent) => {
    e?.stopPropagation();
    setSpeechStatus(1);
    start();
  };
  const onTouchEnd = () => {
    console.log('touch end')
    setSpeechStatus(0)
    stop()
  };

  const handleTouchStart = (e: CommonEvent) => {
    console.log('touch start')
    // fix 解决pc端长按呼出右键菜单
    // e.preventDefault();
    // fix 解决移动端长按依旧穿透
    // e.stopPropagation();
  };

  onStop(async (res) => {
    console.log("record stop:", res);
    if (!agentId || !res) {
      return;
    }
    beforeSend()
    
    
    // 以二进制方式读取文件
    const response = await speechToText(agentId, res.tempFilePath)
    console.log(response,111)
    if(isSuccess(response.status)){
      console.log(response.data)
      const msg = response.data?.text ?? ''
      if(!msg.length){
        return;
      }
      onSend(msg)
      return 
    }
    onError()
  });


  const idle = speechStatus === 0;

  return <>
    {/* <TextInputBar onIconClick={handleTextInputBarSwitch}></TextInputBar> */}
    <View className="px-16 py-12">
      <View className={`flex bg-white gap-6 items-center p-16 rounded-10 ${style.speechButton} ${ idle ? '': style.speechButtonActive}`}>
        {idle && <View className="flex items-center" onClick={onIconClick}><IconKeyboard/></View>}
        <View 
          className="flex-1 flex items-center justify-center"
          onLongPress={onLongPress}
          onTouchStart={handleTouchStart}
          onTouchEnd={onTouchEnd}
        >
          <Text className={`text-16 leading-22 font-medium ${idle ? '':'hidden'}`}>按住说话</Text>
        </View>
      </View>
    </View>  
  </>
}