'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="max-w-2xl mx-auto bg-white rounded-lg shadow-lg p-6">
        <h1 className="text-2xl font-bold mb-6 text-center">MP3转换测试</h1>
        
        <div className="space-y-4">
          {/* 录音控制 */}
          <div className="flex justify-center space-x-4">
            {!isRecording ? (
              <button
                onClick={startRecording}
                className="px-6 py-3 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
              >
                开始录音
              </button>
            ) : (
              <button
                onClick={stopRecording}
                className="px-6 py-3 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
              >
                停止录音
              </button>
            )}
          </div>

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

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

          {mp3Blob && (
            <div className="bg-green-50 p-4 rounded-lg">
              <h3 className="font-medium mb-2">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 px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
              >
                下载MP3文件
              </button>
            </div>
          )}

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