import { View, Text, type CommonEvent } from "@tarojs/components"
import IconKeyboard from "@/components/icon/IconKeyboard"
import IconStop from "@/components/icon/IconStop"
import { useVoiceRecord } from "@/components/voice-recorder";
import { useState } from "react";
import style from './index.module.less'
import { speechToText } from "@/service/chat";
import { isSuccess } from "@/utils";
import { useTextChat } from "@/store/textChatStore";
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 {messageStopHandle} = useTextChat()
  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()
    
    
    // 以二进制方式读取文件
    try{
      const response = await speechToText(agentId, res.tempFilePath)
      if(isSuccess(response.status)){
        // console.log(response.data)
        const msg = response.data?.text ?? ''
        onSend(msg)
      }
    }catch(e){
      console.log(e)
      onError()
    }
  });

  const handleStopClick = ()=> {
    messageStopHandle?.();
  }


  const idle = speechStatus === 0;

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