'use client'

import { ExtendedMessage } from '@/atoms/im'
import { useNimMsgContext } from '@/context/NimChat/useNimChat'
import { useVoiceTTS } from '@/hooks/useVoiceTTS'
import * as React from 'react'
import { useChatConfig } from '../../context/chatConfig'
import { LoadingIcon } from '@/components/ui/button'
import { WaveAnimation } from '@/components/ui/wave-animation'
import {
  extractTextForVoice,
  calculateAudioDuration,
  formatAudioDuration,
} from '@/utils/textParser'

const ChatAudioTag = ({ message }: { message: ExtendedMessage }) => {
  const { audioPlayer } = useNimMsgContext()
  const { aiInfo, aiId } = useChatConfig()
  const { dialoguePitch, dialogueSpeechRate, voiceType } = aiInfo || {}

  const { isGenerating, generateAudioUrl } = useVoiceTTS({
    cacheEnabled: true,
    needCheckSufficient: true,
  })

  const audioText = extractTextForVoice(message.text || '')

  // 计算预估的音频时长
  const estimatedDuration = React.useMemo(() => {
    return calculateAudioDuration(
      message.text || '',
      typeof dialogueSpeechRate === 'number' ? dialogueSpeechRate : 0
    )
  }, [message.text, dialogueSpeechRate])

  // 格式化时长显示
  const formattedDuration = formatAudioDuration(estimatedDuration)

  const isPlaying = audioPlayer?.isPlaying(message.messageClientId)

  const handlePlay = async () => {
    const audioUrl = await generateAudioUrl({
      text: audioText,
      voiceType: voiceType,
      speechRate: dialogueSpeechRate,
      pitchRate: dialoguePitch,
      aiId: aiId,
    })
    if (!audioUrl) {
      return
    }
    audioPlayer?.play(message.messageClientId, audioUrl)
  }

  // const duration = message.duration;

  const renderIcon = () => {
    if (isGenerating) {
      return <LoadingIcon className="!text-[16px] leading-none" />
    }

    if (isPlaying) {
      return <WaveAnimation className="text-txt-primary-normal animate-pulse" />
    }

    return <i className="iconfont icon-Play leading-none" />
  }

  // const renderDuration = () => {
  //   if (message.duration) {
  //     return <span className="txt-label-s">{message.duration}</span>
  //   }
  // }

  if (!audioText) {
    return null
  }

  return (
    <div
      className="bg-surface-float-normal hover:bg-surface-float-hover absolute -top-3 left-0 flex cursor-pointer items-center gap-2 rounded-l-sm rounded-tr-sm px-3 py-1"
      onClick={handlePlay}
    >
      <div className="flex h-4 w-4 items-center">{renderIcon()}</div>
      <span className="txt-label-s">{formattedDuration}</span>
    </div>
  )
}

export default ChatAudioTag
