'use client'

import React, { createContext, useContext, useRef, useState, useCallback, useEffect } from 'react'

interface AudioPlayerContextType {
  currentPlayingId: string | null
  play: (audioUrl: string, id: string) => void
  stop: () => void
  isPlaying: (id: string) => boolean
}

const AudioPlayerContext = createContext<AudioPlayerContextType | undefined>(undefined)

export const AudioPlayerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const audioRef = useRef<HTMLAudioElement | null>(null)
  const [currentPlayingId, setCurrentPlayingId] = useState<string | null>(null)

  const stop = useCallback(() => {
    if (audioRef.current) {
      audioRef.current.pause()
      audioRef.current.currentTime = 0
    }
    setCurrentPlayingId(null)
  }, [])

  const play = useCallback(
    (audioUrl: string, id: string) => {
      // 如果正在播放同一个音频，则停止
      if (currentPlayingId === id) {
        stop()
        return
      }

      // 停止当前播放的音频
      stop()

      // 创建新的音频实例
      const audio = new Audio(audioUrl)
      audioRef.current = audio
      setCurrentPlayingId(id)

      // 播放结束后重置状态
      audio.onended = () => {
        setCurrentPlayingId(null)
      }

      // 播放出错时重置状态
      audio.onerror = () => {
        console.error('音频播放失败')
        setCurrentPlayingId(null)
      }

      // 开始播放
      audio.play().catch((error) => {
        console.error('音频播放失败:', error)
        setCurrentPlayingId(null)
      })
    },
    [currentPlayingId, stop]
  )

  const isPlaying = useCallback(
    (id: string) => {
      return currentPlayingId === id
    },
    [currentPlayingId]
  )

  // 当组件卸载时停止播放
  useEffect(() => {
    return () => {
      if (audioRef.current) {
        audioRef.current.pause()
        audioRef.current.currentTime = 0
        audioRef.current = null
      }
    }
  }, [])

  return (
    <AudioPlayerContext.Provider value={{ currentPlayingId, play, stop, isPlaying }}>
      {children}
    </AudioPlayerContext.Provider>
  )
}

export const useAudioPlayer = () => {
  const context = useContext(AudioPlayerContext)
  if (context === undefined) {
    throw new Error('useAudioPlayer must be used within an AudioPlayerProvider')
  }
  return context
}
