import { ref, reactive, onMounted, onUnmounted } from 'vue'

export const useSpeechSynthesis = () => {
  const isSpeaking = ref(false)
  const isPaused = ref(false)
  const speakingText = ref('')
  const speakingProgress = ref(0)
  const availableVoices = ref([])
  const selectedVoice = ref(null)
  const isSpeechAvailable = ref(false)
  const errorMessage = ref('')
  const utteranceRef = ref(null)
  const currentTextRef = ref('')
  const currentIndexRef = ref(0)
  const speakingTimerRef = ref(null)
  const isInitializedRef = ref(false)

  const checkSpeechAvailability = () => {
    if ('speechSynthesis' in window) {
      console.log('Speech synthesis API is available')
      isSpeechAvailable.value = true
      return true
    } else {
      console.log('Speech synthesis API is not available')
      isSpeechAvailable.value = false
      errorMessage.value = '语音合成功能在当前浏览器中不可用'
      return false
    }
  }

  const getVoices = () => {
    try {
      const voices = window.speechSynthesis.getVoices()
      console.log('Available voices:', voices)
      availableVoices.value = voices
      
      const chineseVoice = voices.find(voice => 
        voice.lang.includes('zh') || voice.lang.includes('Chinese')
      )
      
      if (chineseVoice) {
        console.log('Selected Chinese voice:', chineseVoice)
        selectedVoice.value = chineseVoice
      } else {
        console.log('No Chinese voice found, using default')
        if (voices.length > 0) {
          selectedVoice.value = voices[0]
        } else {
          console.log('No voices available')
          errorMessage.value = '没有可用的语音'
        }
      }
      
      isInitializedRef.value = true
    } catch (error) {
      console.error('Error getting voices:', error)
      errorMessage.value = '获取语音列表失败'
    }
  }

  onMounted(() => {
    console.log('Initializing speech synthesis...')
    
    if (!checkSpeechAvailability()) {
      return
    }
    
    console.log('speechSynthesis state:', window.speechSynthesis)
    
    getVoices()
    
    if (window.speechSynthesis.onvoiceschanged !== undefined) {
      window.speechSynthesis.onvoiceschanged = getVoices
    }
  })

  onUnmounted(() => {
    if ('speechSynthesis' in window) {
      window.speechSynthesis.cancel()
    }
    if (speakingTimerRef.value) {
      clearInterval(speakingTimerRef.value)
    }
  })

  const speak = (text, options = {}) => {
    console.log('speak called with text length:', text.length)
    
    if (!isSpeechAvailable.value) {
      console.log('Speech synthesis is not available')
      errorMessage.value = '语音合成功能不可用'
      return
    }
    
    if (!isInitializedRef.value) {
      console.log('Speech synthesis not initialized yet')
      errorMessage.value = '语音合成正在初始化，请稍后再试'
      return
    }
    
    if (!text) {
      console.log('No text provided')
      return
    }

    try {
      console.log('speechSynthesis state:', window.speechSynthesis)
      console.log('speechSynthesis pending:', window.speechSynthesis.pending)
      console.log('speechSynthesis speaking:', window.speechSynthesis.speaking)
      
      window.speechSynthesis.cancel()
      console.log('Cancelled any pending speech')
      
      const {
        lang = 'zh-CN',
        rate = 1,
        pitch = 1,
        volume = 1,
        voice = selectedVoice.value,
        onProgress
      } = options

      console.log('Creating utterance with voice:', voice)
      console.log('Language:', lang)
      console.log('Rate:', rate)
      
      const utterance = new SpeechSynthesisUtterance(text)
      utterance.lang = lang
      utterance.rate = rate
      utterance.pitch = pitch
      utterance.volume = volume
      
      if (voice) {
        utterance.voice = voice
        console.log('Voice set successfully')
      } else {
        console.log('No voice selected, using default')
      }

      speakingText.value = text
      speakingProgress.value = 0
      currentTextRef.value = text
      currentIndexRef.value = 0

      utterance.onstart = () => {
        console.log('Speech started')
        isSpeaking.value = true
        isPaused.value = false
        errorMessage.value = ''
        
        if (speakingTimerRef.value) {
          clearInterval(speakingTimerRef.value)
        }
        speakingTimerRef.value = setInterval(() => {
          currentIndexRef.value += 1
          const progress = Math.min((currentIndexRef.value / text.length) * 100, 100)
          speakingProgress.value = progress
          if (onProgress) {
            onProgress(progress)
          }
        }, 100)
      }

      utterance.onend = () => {
        console.log('Speech ended')
        isSpeaking.value = false
        isPaused.value = false
        speakingProgress.value = 100
        if (onProgress) {
          onProgress(100)
        }
        if (speakingTimerRef.value) {
          clearInterval(speakingTimerRef.value)
          speakingTimerRef.value = null
        }
      }

      utterance.onerror = (event) => {
        console.error('Speech synthesis error:', event)
        console.error('Error message:', event.message)
        console.error('Error name:', event.name)
        console.error('Error details:', event)
        isSpeaking.value = false
        isPaused.value = false
        errorMessage.value = '语音合成失败，请检查浏览器设置'
        if (speakingTimerRef.value) {
          clearInterval(speakingTimerRef.value)
          speakingTimerRef.value = null
        }
      }

      utteranceRef.value = utterance
      console.log('About to speak...')
      window.speechSynthesis.speak(utterance)
      console.log('speak() called successfully')
    } catch (error) {
      console.error('Error in speak function:', error)
      isSpeaking.value = false
      isPaused.value = false
      errorMessage.value = '语音合成失败: ' + error.message
    }
  }

  const pause = () => {
    if (isSpeaking.value) {
      window.speechSynthesis.pause()
      isPaused.value = true
      if (speakingTimerRef.value) {
        clearInterval(speakingTimerRef.value)
      }
    }
  }

  const resume = () => {
    if (isPaused.value) {
      window.speechSynthesis.resume()
      isPaused.value = false
      
      if (!speakingTimerRef.value && currentTextRef.value) {
        speakingTimerRef.value = setInterval(() => {
          currentIndexRef.value += 1
          const progress = Math.min((currentIndexRef.value / currentTextRef.value.length) * 100, 100)
          speakingProgress.value = progress
        }, 100)
      }
    }
  }

  const stop = () => {
    window.speechSynthesis.cancel()
    isSpeaking.value = false
    isPaused.value = false
    speakingText.value = ''
    speakingProgress.value = 0
    currentTextRef.value = ''
    currentIndexRef.value = 0
    if (speakingTimerRef.value) {
      clearInterval(speakingTimerRef.value)
      speakingTimerRef.value = null
    }
    utteranceRef.value = null
  }

  const setRate = (rate) => {
    if (utteranceRef.value) {
      utteranceRef.value.rate = rate
    }
  }

  const setVolume = (volume) => {
    if (utteranceRef.value) {
      utteranceRef.value.volume = volume
    }
  }

  return {
    speak,
    pause,
    resume,
    stop,
    isSpeaking,
    isPaused,
    speakingText,
    speakingProgress,
    availableVoices,
    selectedVoice,
    setSelectedVoice: (voice) => { selectedVoice.value = voice },
    setRate,
    setVolume,
    isSpeechAvailable,
    errorMessage
  }
}