import { useDevicesList, useUserMedia } from '@vueuse/core'

export const readBlobAsBase64 = (blob: Blob): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => {
      try {
        const base64Data = (reader.result as string).split(',')[2]
        resolve(base64Data)
      } catch (error) {
        reject(error)
      }
    }
    reader.onerror = () => {
      reject(new Error('Failed to read file'))
    }
    reader.readAsDataURL(blob)
  })
}

interface UseLiveProps {
  enabledUserMedia: boolean
  onStart?: () => void
  onRecord?: (data: Blob) => void
  onStop?: (blob: Blob) => void
}

export function useLive({ enabledUserMedia = true, onStart, onRecord, onStop }: UseLiveProps) {
  const startTime = ref(0)
  const endTime = ref(0)
  const duration = computed(() => (endTime.value - startTime.value) / 1000)
  const currentTime = ref(0)

  // 获取设备列表并设置默认设备
  const { videoInputs: cameras, audioInputs: microphones } = useDevicesList({ requestPermissions: true })
  const currentCamera = computed(() => cameras.value[0]?.deviceId)
  const currentMicrophone = computed(() => microphones.value[0]?.deviceId)

  // 创建媒体流
  const { stream } = useUserMedia({
    enabled: enabledUserMedia,
    constraints: { video: { deviceId: currentCamera as any }, audio: { deviceId: currentMicrophone as any } },
  })

  // 录像设置
  const recordedChunks = ref<Blob[]>([])
  let mediaRecorder: MediaRecorder | null = null
  let timeUpdateInterval: number | null = null

  // 初始化MediaRecorder
  const initializeMediaRecorder = () => {
    if (!stream.value) return
    mediaRecorder = new MediaRecorder(stream.value, { mimeType: 'video/webm' })
    mediaRecorder.ondataavailable = handleDataAvailable
    mediaRecorder.onstart = handleStart
    mediaRecorder.onstop = handleStop
  }

  // 数据可用时处理
  const handleDataAvailable = (event: BlobEvent) => {
    if (event.data.size > 0) {
      recordedChunks.value.push(event.data)
      onRecord && onRecord(event.data)
    }
  }

  // 录像开始时处理
  const handleStart = () => {
    startTime.value = Date.now()
    onStart && onStart()

    // Update currentTime every 100ms while recording
    timeUpdateInterval = setInterval(() => {
      currentTime.value = Math.floor((Date.now() - startTime.value) / 1000)
    }, 1000 * 5)
  }

  // 录像停止时处理
  const handleStop = () => {
    endTime.value = Date.now()
    const blob = new Blob(recordedChunks.value, { type: mediaRecorder?.mimeType })
    onStop && onStop(blob)
    recordedChunks.value = []

    // Clear the interval when recording stops
    if (timeUpdateInterval !== null) {
      clearInterval(timeUpdateInterval)
      timeUpdateInterval = null
    }
  }

  // 开始录制
  const start = () => {
    if (!mediaRecorder) initializeMediaRecorder()
    recordedChunks.value = []
    mediaRecorder?.start(100) // 每100ms触发一次dataavailable事件
  }

  // 停止录制
  const stop = () => {
    if (mediaRecorder) mediaRecorder.stop()
  }

  return { stream, start, stop, startTime, endTime, duration, currentTime }
}
