'use client'

import React, { useState, useRef } from 'react'
import { convertToMp3, createAudioConverter } from '@/lib/audio/audio-converter'
import { toast } from 'sonner'

export default function TestMp3Conversion() {
  const [isRecording, setIsRecording] = useState(false)
  const [isProcessing, setIsProcessing] = useState(false)
  const [mp3Blob, setMp3Blob] = useState<Blob | null>(null)
  const [originalBlob, setOriginalBlob] = useState<Blob | null>(null)

  const mediaRecorderRef = useRef<MediaRecorder | null>(null)
  const audioChunksRef = useRef<Blob[]>([])

  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
      const mediaRecorder = new MediaRecorder(stream)
      mediaRecorderRef.current = mediaRecorder
      audioChunksRef.current = []

      mediaRecorder.ondataavailable = (event) => {
        audioChunksRef.current.push(event.data)
      }

      mediaRecorder.onstop = async () => {
        const originalAudioBlob = new Blob(audioChunksRef.current, { type: 'audio/webm' })
        setOriginalBlob(originalAudioBlob)

        setIsProcessing(true)
        try {
          const mp3Blob = await convertToMp3(originalAudioBlob, {
            sampleRate: 44100,
            bitRate: 128,
            channels: 1,
          })
          setMp3Blob(mp3Blob)
          toast.success('MP3转换完成！')
        } catch (error) {
          console.error('MP3转换失败:', error)
          toast.error('MP3转换失败')
        } finally {
          setIsProcessing(false)
        }

        stream.getTracks().forEach((track) => track.stop())
      }

      mediaRecorder.start()
      setIsRecording(true)
    } catch (error) {
      console.error('录音失败:', error)
      toast.error('录音失败')
    }
  }

  const stopRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop()
      setIsRecording(false)
    }
  }

  const downloadMp3 = () => {
    if (mp3Blob) {
      const url = URL.createObjectURL(mp3Blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `test-recording-${Date.now()}.mp3`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      toast.success('MP3文件已下载')
    }
  }

  const downloadOriginal = () => {
    if (originalBlob) {
      const url = URL.createObjectURL(originalBlob)
      const a = document.createElement('a')
      a.href = url
      a.download = `original-recording-${Date.now()}.webm`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      toast.success('原始文件已下载')
    }
  }

  return (
    <div className="min-h-screen bg-gray-100 p-8">
      <div className="mx-auto max-w-2xl rounded-lg bg-white p-6 shadow-lg">
        <h1 className="mb-6 text-center text-2xl font-bold">MP3转换测试</h1>

        <div className="space-y-4">
          {/* 录音控制 */}
          <div className="flex justify-center space-x-4">
            {!isRecording ? (
              <button
                onClick={startRecording}
                className="rounded-lg bg-red-500 px-6 py-3 text-white transition-colors hover:bg-red-600"
              >
                开始录音
              </button>
            ) : (
              <button
                onClick={stopRecording}
                className="rounded-lg bg-gray-500 px-6 py-3 text-white transition-colors hover:bg-gray-600"
              >
                停止录音
              </button>
            )}
          </div>

          {/* 状态显示 */}
          <div className="text-center">
            {isRecording && <p className="font-medium text-red-500">🔴 正在录音...</p>}
            {isProcessing && <p className="font-medium text-blue-500">⏳ 正在转换为MP3...</p>}
          </div>

          {/* 文件信息 */}
          {originalBlob && (
            <div className="rounded-lg bg-gray-50 p-4">
              <h3 className="mb-2 font-medium">原始文件信息</h3>
              <p>大小: {(originalBlob.size / 1024).toFixed(1)} KB</p>
              <p>类型: {originalBlob.type}</p>
              <button
                onClick={downloadOriginal}
                className="mt-2 rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
              >
                下载原始文件
              </button>
            </div>
          )}

          {mp3Blob && (
            <div className="rounded-lg bg-green-50 p-4">
              <h3 className="mb-2 font-medium">MP3文件信息</h3>
              <p>大小: {(mp3Blob.size / 1024).toFixed(1)} KB</p>
              <p>类型: {mp3Blob.type}</p>
              <p>
                压缩率:{' '}
                {originalBlob
                  ? `${((1 - mp3Blob.size / originalBlob.size) * 100).toFixed(1)}%`
                  : 'N/A'}
              </p>
              <button
                onClick={downloadMp3}
                className="mt-2 rounded bg-green-500 px-4 py-2 text-white hover:bg-green-600"
              >
                下载MP3文件
              </button>
            </div>
          )}

          {/* 音频播放测试 */}
          {mp3Blob && (
            <div className="rounded-lg bg-yellow-50 p-4">
              <h3 className="mb-2 font-medium">音频播放测试</h3>
              <audio controls className="w-full">
                <source src={URL.createObjectURL(mp3Blob)} type="audio/mp3" />
                您的浏览器不支持音频播放。
              </audio>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
