import React, { useState, useCallback, useEffect } from 'react';
import {
  Mic,
  Volume2,
  Download,
  RefreshCw,
  Settings,
  Wand2,
  CheckCircle,
  XCircle,
  Loader2,
  Music,
  FileAudio,
  Trash2,
  Star,
  Users,
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';
import { useNotifications } from '../../components/NotificationSystem';
import SystemVoiceSelector from '../../components/SystemVoiceSelector';
import {
  AudioUploadRequest,
  AudioUploadResponse,
  VoiceCloneRequest,
  VoiceCloneResponse,
  VoiceInfo,
  GetVoicesResponse,
  SpeechGenerationRequest,
  SpeechGenerationResponse,
  VoiceCloneStatus,
  SpeechGenerationStatus,
  AudioFileInfo,
  VoiceCloneState,
  SpeechGenerationState,
  SpeechGenerationRecord,
  SpeechGenerationRecordStatus
} from '../../types/voiceClone';
import { SystemVoice } from '../../types/systemVoice';

/**
 * 声音克隆与TTS工具
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
const VoiceCloneTool: React.FC = () => {
  const { addNotification } = useNotifications();

  // ============= 状态管理 =============
  
  // 音频上传状态
  const [audioFile, setAudioFile] = useState<AudioFileInfo | null>(null);

  // 声音克隆状态
  const [cloneText, setCloneText] = useState('');
  const [customVoiceId, setCustomVoiceId] = useState('');
  const [cloneState, setCloneState] = useState<VoiceCloneState>({
    status: VoiceCloneStatus.IDLE
  });

  // 合并后的状态：是否正在处理（上传+克隆）
  const [isProcessingClone, setIsProcessingClone] = useState(false);

  // 音色管理状态
  const [voices, setVoices] = useState<VoiceInfo[]>([]);
  const [selectedVoiceId, setSelectedVoiceId] = useState<string>('');
  const [isLoadingVoices, setIsLoadingVoices] = useState(false);

  // 系统音色状态
  const [selectedSystemVoice, setSelectedSystemVoice] = useState<SystemVoice | null>(null);
  const [voiceSource, setVoiceSource] = useState<'system' | 'custom'>('system');

  // 语音生成状态
  const [speechRequest, setSpeechRequest] = useState<SpeechGenerationRequest>({
    text: '',
    voice_id: '',
    speed: 1.0,
    vol: 1.0,
    emotion: 'calm'
  });
  const [speechState, setSpeechState] = useState<SpeechGenerationState>({
    status: SpeechGenerationStatus.IDLE
  });

  // 语音生成记录
  const [speechRecords, setSpeechRecords] = useState<SpeechGenerationRecord[]>([]);
  const [loadingRecords, setLoadingRecords] = useState(false);

  // ============= 数据加载函数 =============

  // 加载语音生成记录
  const loadSpeechRecords = useCallback(async () => {
    setLoadingRecords(true);
    try {
      const records = await invoke<SpeechGenerationRecord[]>('get_speech_generation_records', {
        limit: 50 // 限制最近50条记录
      });
      console.log('获取到的语音生成记录:', records);
      setSpeechRecords(records);
    } catch (error) {
      console.error('加载语音生成记录失败:', error);
      addNotification({
        type: 'error',
        title: '加载失败',
        message: `加载语音生成记录失败: ${error}`
      });
    } finally {
      setLoadingRecords(false);
    }
  }, [addNotification]);

  // 删除语音生成记录
  const deleteSpeechRecord = useCallback(async (recordId: string) => {
    if (!window.confirm('确定要删除这条语音生成记录吗？')) {
      return;
    }

    try {
      await invoke('delete_speech_generation_record', {
        recordId
      });

      addNotification({
        type: 'success',
        title: '删除成功',
        message: '语音生成记录已删除'
      });

      // 刷新记录列表
      await loadSpeechRecords();
    } catch (error) {
      console.error('删除语音生成记录失败:', error);
      addNotification({
        type: 'error',
        title: '删除失败',
        message: `删除语音生成记录失败: ${error}`
      });
    }
  }, [addNotification, loadSpeechRecords]);

  // ============= 音色管理功能 =============

  const loadVoices = useCallback(async () => {
    setIsLoadingVoices(true);
    try {
      const response = await invoke<GetVoicesResponse>('get_voices');

      if (response.status && response.data) {
        setVoices(response.data);

        // 如果没有选中的音色且有可用音色，选择第一个
        if (!selectedVoiceId && response.data && response.data.length > 0) {
          const firstVoice = response.data[0];
          setSelectedVoiceId(firstVoice.voice_id);
          setSpeechRequest(prev => ({
            ...prev,
            voice_id: firstVoice.voice_id
          }));
        }
      }
    } catch (error) {
      console.error('获取音色列表失败:', error);
      addNotification({
        type: 'error',
        title: '获取音色列表失败',
        message: `获取失败: ${error}`
      });
    } finally {
      setIsLoadingVoices(false);
    }
  }, [selectedVoiceId, addNotification]);

  // ============= 音频上传功能 =============

  const handleFileSelect = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [{
          name: 'Audio Files',
          extensions: ['wav', 'mp3', 'flac', 'm4a', 'aac', 'ogg']
        }]
      });

      if (selected && typeof selected === 'string') {
        const file = new File([], selected.split('/').pop() || 'audio');
        const audioInfo: AudioFileInfo = {
          file,
          name: file.name,
          size: 0, // 实际应该获取文件大小
          type: file.type || 'audio/wav',
          preview_url: selected
        };
        
        setAudioFile(audioInfo);
        addNotification({
          type: 'success',
          title: '文件选择成功',
          message: `已选择音频文件: ${audioInfo.name}`
        });
      }
    } catch (error) {
      console.error('文件选择失败:', error);
      addNotification({
        type: 'error',
        title: '文件选择失败',
        message: `选择文件时出错: ${error}`
      });
    }
  }, [addNotification]);



  // ============= 声音克隆功能 =============

  const handleVoiceClone = useCallback(async () => {
    if (!cloneText.trim()) {
      addNotification({
        type: 'warning',
        title: '请输入克隆文本',
        message: '请输入用于声音克隆的文本内容'
      });
      return;
    }

    if (!audioFile?.preview_url) {
      addNotification({
        type: 'warning',
        title: '请先选择音频文件',
        message: '请先选择参考音频文件'
      });
      return;
    }

    setIsProcessingClone(true);
    setCloneState({
      status: VoiceCloneStatus.PROCESSING,
      progress: '正在上传音频文件...'
    });

    try {
      // 第一步：上传音频文件
      const uploadRequest: AudioUploadRequest = {
        audio_file_path: audioFile.preview_url,
        purpose: 'voice_clone'
      };

      const uploadResponse = await invoke<AudioUploadResponse>('upload_audio_file', { request: uploadRequest });

      if (!uploadResponse.status) {
        throw new Error(uploadResponse.msg || '音频上传失败');
      }

      // 更新进度
      setCloneState({
        status: VoiceCloneStatus.PROCESSING,
        progress: '音频上传成功，正在克隆声音...'
      });

      // 第二步：执行声音克隆
      const finalVoiceId = customVoiceId.trim() || `voice_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;

      const cloneRequest: VoiceCloneRequest = {
        text: cloneText,
        model: 'speech-02-hd',
        need_noise_reduction: true,
        voice_id: finalVoiceId,
        prefix: 'BoWong-',
        audio_file_path: audioFile.preview_url
      };

      const cloneResponse = await invoke<VoiceCloneResponse>('clone_voice', { request: cloneRequest });

      if (cloneResponse.status && cloneResponse.data) {
        setCloneState({
          status: VoiceCloneStatus.SUCCESS,
          result: cloneResponse
        });

        const voiceId = cloneResponse.extra?.voice_id || '未知';
        addNotification({
          type: 'success',
          title: '声音克隆成功',
          message: `新音色ID: ${voiceId}`
        });

        // 刷新音色列表
        await loadVoices();

        // 清空表单
        setCloneText('');
        setCustomVoiceId('');
      } else {
        throw new Error(cloneResponse.msg || '克隆失败');
      }
    } catch (error) {
      console.error('声音克隆失败:', error);
      setCloneState({
        status: VoiceCloneStatus.ERROR,
        error: String(error)
      });

      addNotification({
        type: 'error',
        title: '声音克隆失败',
        message: `克隆失败: ${error}`
      });
    } finally {
      setIsProcessingClone(false);
    }
  }, [cloneText, audioFile, customVoiceId, addNotification, loadVoices]);

  // ============= 音色管理功能 =============

  const handleVoiceSelect = useCallback((voiceId: string) => {
    setSelectedVoiceId(voiceId);
    setVoiceSource('custom');
    setSpeechRequest(prev => ({
      ...prev,
      voice_id: voiceId
    }));
  }, []);

  // 系统音色选择处理
  const handleSystemVoiceSelect = useCallback((voiceId: string, voice: SystemVoice) => {
    setSelectedSystemVoice(voice);
    setVoiceSource('system');
    setSpeechRequest(prev => ({
      ...prev,
      voice_id: voiceId
    }));
  }, []);

  // ============= 语音生成功能 =============

  const handleGenerateSpeech = useCallback(async () => {
    if (!speechRequest.text.trim()) {
      addNotification({
        type: 'warning',
        title: '请输入要合成的文本',
        message: '请输入要转换为语音的文本内容'
      });
      return;
    }

    if (!speechRequest.voice_id) {
      addNotification({
        type: 'warning',
        title: '请选择音色',
        message: '请选择要使用的音色'
      });
      return;
    }

    setSpeechState({
      status: SpeechGenerationStatus.GENERATING,
      progress: '正在生成语音...'
    });

    try {
      const response = await invoke<SpeechGenerationResponse>('generate_speech', { 
        request: speechRequest 
      });

      if (response.status && response.data) {
        setSpeechState({
          status: SpeechGenerationStatus.SUCCESS,
          result: response
        });
        
        addNotification({
          type: 'success',
          title: '语音生成成功',
          message: '语音已成功生成，可以播放或下载'
        });

        // 刷新语音生成记录列表
        await loadSpeechRecords();
      } else {
        throw new Error(response.msg || '生成失败');
      }
    } catch (error) {
      console.error('语音生成失败:', error);
      setSpeechState({
        status: SpeechGenerationStatus.ERROR,
        error: String(error)
      });
      
      addNotification({
        type: 'error',
        title: '语音生成失败',
        message: `生成失败: ${error}`
      });
    }
  }, [speechRequest, addNotification, loadSpeechRecords]);

  // ============= 初始化 =============

  useEffect(() => {
    loadVoices();
    loadSpeechRecords();
  }, [loadVoices, loadSpeechRecords]);

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="page-header flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-12 h-12 bg-gradient-to-br from-purple-500 to-pink-600 rounded-xl flex items-center justify-center shadow-lg hover:shadow-xl transition-all duration-300">
            <Mic className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-900 to-purple-600 bg-clip-text text-transparent">
              声音克隆与TTS工具
            </h1>
            <p className="text-gray-600 text-lg">专业的语音合成和声音克隆功能</p>
          </div>
        </div>

        <button
          onClick={loadVoices}
          disabled={isLoadingVoices}
          className="flex items-center gap-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          <RefreshCw className={`w-4 h-4 ${isLoadingVoices ? 'animate-spin' : ''}`} />
          刷新音色
        </button>
      </div>

      {/* 主要内容区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 左侧：声音克隆 */}
        <div className="space-y-6">
          {/* 声音克隆卡片 */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div className="flex items-center gap-3 mb-4">
              <Wand2 className="w-5 h-5 text-purple-600" />
              <h3 className="text-lg font-semibold text-gray-900">声音克隆</h3>
            </div>

            <div className="space-y-4">
              {/* 音频文件选择 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  参考音频文件
                </label>
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-purple-400 transition-colors">
                  {audioFile ? (
                    <div className="flex items-center justify-center gap-3">
                      <FileAudio className="w-6 h-6 text-purple-600" />
                      <div className="text-left">
                        <p className="font-medium text-gray-900 text-sm">{audioFile.name}</p>
                        <p className="text-xs text-gray-500">
                          {audioFile.type} • {(audioFile.size / 1024 / 1024).toFixed(2)} MB
                        </p>
                      </div>
                      <button
                        onClick={() => setAudioFile(null)}
                        className="ml-2 text-gray-400 hover:text-red-600 transition-colors"
                        title="移除文件"
                      >
                        <XCircle className="w-4 h-4" />
                      </button>
                    </div>
                  ) : (
                    <div>
                      <Music className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                      <p className="text-gray-600 text-sm mb-1">选择参考音频文件</p>
                      <p className="text-xs text-gray-500">支持 WAV, MP3, FLAC, M4A, AAC, OGG 格式</p>
                    </div>
                  )}

                  <button
                    onClick={handleFileSelect}
                    className="mt-3 px-3 py-1.5 text-sm bg-purple-600 text-white rounded-md hover:bg-purple-700 transition-colors"
                  >
                    {audioFile ? '重新选择' : '选择文件'}
                  </button>
                </div>
              </div>

              {/* 克隆文本输入 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  克隆文本
                </label>
                <textarea
                  value={cloneText}
                  onChange={(e) => setCloneText(e.target.value)}
                  placeholder="请输入用于声音克隆的文本内容..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent resize-none"
                  rows={3}
                />
              </div>

              {/* 自定义音色ID */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  自定义音色ID（可选）
                </label>
                <input
                  type="text"
                  value={customVoiceId}
                  onChange={(e) => setCustomVoiceId(e.target.value)}
                  placeholder="留空将自动生成"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                />
              </div>

              {/* 克隆按钮 */}
              <button
                onClick={handleVoiceClone}
                disabled={isProcessingClone}
                className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isProcessingClone ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    处理中...
                  </>
                ) : (
                  <>
                    <Wand2 className="w-4 h-4" />
                    生成克隆
                  </>
                )}
              </button>

              {/* 克隆状态显示 */}
              {cloneState.status !== VoiceCloneStatus.IDLE && (
                <div className="p-3 rounded-lg border">
                  <div className="flex items-center gap-2 text-sm">
                    {cloneState.status === VoiceCloneStatus.SUCCESS && (
                      <>
                        <CheckCircle className="w-4 h-4 text-green-600" />
                        <span className="text-green-600">克隆成功</span>
                      </>
                    )}
                    {cloneState.status === VoiceCloneStatus.ERROR && (
                      <>
                        <XCircle className="w-4 h-4 text-red-600" />
                        <span className="text-red-600">克隆失败: {cloneState.error}</span>
                      </>
                    )}
                    {cloneState.status === VoiceCloneStatus.PROCESSING && (
                      <>
                        <Loader2 className="w-4 h-4 animate-spin text-purple-600" />
                        <span className="text-purple-600">{cloneState.progress}</span>
                      </>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>

        </div>

        {/* 右侧：音色管理和语音合成 */}
        <div className="space-y-6">
          {/* 音色选择卡片 */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div className="flex items-center gap-3 mb-4">
              <Volume2 className="w-5 h-5 text-blue-600" />
              <h3 className="text-lg font-semibold text-gray-900">音色选择</h3>
            </div>

            {/* 音色来源切换 */}
            <div className="flex items-center gap-4 mb-4">
              <div className="flex items-center gap-2">
                <input
                  type="radio"
                  id="system-voice"
                  name="voice-source"
                  checked={voiceSource === 'system'}
                  onChange={() => setVoiceSource('system')}
                  className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                />
                <label htmlFor="system-voice" className="flex items-center gap-2 text-sm font-medium text-gray-700">
                  <Star className="w-4 h-4 text-blue-600" />
                  系统音色
                </label>
              </div>
              <div className="flex items-center gap-2">
                <input
                  type="radio"
                  id="custom-voice"
                  name="voice-source"
                  checked={voiceSource === 'custom'}
                  onChange={() => setVoiceSource('custom')}
                  className="w-4 h-4 text-orange-600 focus:ring-orange-500"
                />
                <label htmlFor="custom-voice" className="flex items-center gap-2 text-sm font-medium text-gray-700">
                  <Users className="w-4 h-4 text-orange-600" />
                  自定义音色
                </label>
              </div>
            </div>

            {/* 系统音色选择器 */}
            {voiceSource === 'system' && (
              <SystemVoiceSelector
                selectedVoiceId={voiceSource === 'system' ? speechRequest.voice_id : ''}
                onVoiceSelect={handleSystemVoiceSelect}
                showSearch={true}
                showTypeFilter={true}
                showGenderFilter={true}
                className="border-0 shadow-none"
              />
            )}

            {/* 自定义音色管理 */}
            {voiceSource === 'custom' && (
              <div>
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <Users className="w-5 h-5 text-orange-600" />
                    <h4 className="text-md font-medium text-gray-900">自定义音色</h4>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-500">{voices.length} 个音色</span>
                    <button
                      onClick={loadVoices}
                      disabled={isLoadingVoices}
                      className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
                      title="刷新音色列表"
                    >
                      <RefreshCw className={`w-4 h-4 ${isLoadingVoices ? 'animate-spin' : ''}`} />
                    </button>
                  </div>
                </div>

                <div className="space-y-3 max-h-64 overflow-y-auto">
                  {isLoadingVoices ? (
                    <div className="flex items-center justify-center py-8">
                      <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
                      <span className="ml-2 text-gray-500">加载中...</span>
                    </div>
                  ) : voices.length === 0 ? (
                    <div className="text-center py-8 text-gray-500">
                      <Volume2 className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                      <p>暂无可用音色</p>
                      <p className="text-sm">请先克隆一个音色</p>
                    </div>
                  ) : (
                    voices.map((voice) => (
                      <div
                        key={voice.voice_id}
                        className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                          voiceSource === 'custom' && selectedVoiceId === voice.voice_id
                            ? 'border-orange-500 bg-orange-50'
                            : 'border-gray-200 hover:border-orange-300'
                        }`}
                        onClick={() => handleVoiceSelect(voice.voice_id)}
                      >
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="font-medium text-gray-900">
                              {voice.voice_name || voice.voice_id}
                            </p>
                            {voice.description && voice.description.length > 0 && (
                              <p className="text-sm text-gray-500">{voice.description.join(', ')}</p>
                            )}
                            {voice.created_time && (
                              <p className="text-xs text-gray-400">创建时间: {voice.created_time}</p>
                            )}
                          </div>
                          <div className="flex items-center gap-2">
                            {voiceSource === 'custom' && selectedVoiceId === voice.voice_id && (
                              <CheckCircle className="w-4 h-4 text-orange-600" />
                            )}
                          </div>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </div>
            )}
          </div>

          {/* 语音合成卡片 */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div className="flex items-center gap-3 mb-4">
              <Settings className="w-5 h-5 text-green-600" />
              <h3 className="text-lg font-semibold text-gray-900">语音合成</h3>
            </div>

            <div className="space-y-4">
              {/* 当前选择的音色信息 */}
              <div className="p-3 bg-gray-50 rounded-lg border">
                <div className="flex items-center gap-2 mb-2">
                  <Volume2 className="w-4 h-4 text-gray-600" />
                  <span className="text-sm font-medium text-gray-700">当前音色</span>
                </div>
                {voiceSource === 'system' && selectedSystemVoice ? (
                  <div className="flex items-center gap-3">
                    <span className="text-lg">{selectedSystemVoice.gender === 'male' ? '👨' : selectedSystemVoice.gender === 'female' ? '👩' : '👶'}</span>
                    <div>
                      <p className="font-medium text-gray-900">{selectedSystemVoice.voice_name}</p>
                      <p className="text-xs text-gray-500">
                        {selectedSystemVoice.voice_name_en && `${selectedSystemVoice.voice_name_en} • `}
                        系统音色 • {selectedSystemVoice.voice_id}
                      </p>
                    </div>
                  </div>
                ) : voiceSource === 'custom' && selectedVoiceId ? (
                  <div className="flex items-center gap-3">
                    <Users className="w-5 h-5 text-orange-600" />
                    <div>
                      <p className="font-medium text-gray-900">
                        {voices.find(v => v.voice_id === selectedVoiceId)?.voice_name || selectedVoiceId}
                      </p>
                      <p className="text-xs text-gray-500">自定义音色 • {selectedVoiceId}</p>
                    </div>
                  </div>
                ) : (
                  <p className="text-sm text-gray-500">请先选择一个音色</p>
                )}
              </div>

              {/* 合成文本输入 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  合成文本
                </label>
                <textarea
                  value={speechRequest.text}
                  onChange={(e) => setSpeechRequest(prev => ({ ...prev, text: e.target.value }))}
                  placeholder="请输入要转换为语音的文本..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent resize-none"
                  rows={3}
                />
              </div>

              {/* 参数控制 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    语速: {speechRequest.speed}
                  </label>
                  <input
                    type="range"
                    min="0.5"
                    max="2"
                    step="0.1"
                    value={speechRequest.speed}
                    onChange={(e) => setSpeechRequest(prev => ({ 
                      ...prev, 
                      speed: parseFloat(e.target.value) 
                    }))}
                    className="w-full"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    音量: {speechRequest.vol}
                  </label>
                  <input
                    type="range"
                    min="0.1"
                    max="2"
                    step="0.1"
                    value={speechRequest.vol}
                    onChange={(e) => setSpeechRequest(prev => ({ 
                      ...prev, 
                      vol: parseFloat(e.target.value) 
                    }))}
                    className="w-full"
                  />
                </div>
              </div>

              {/* 情感选择 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  情感
                </label>
                <select
                  value={speechRequest.emotion}
                  onChange={(e) => setSpeechRequest(prev => ({ 
                    ...prev, 
                    emotion: e.target.value as any 
                  }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
                >
                  <option value="calm">平静</option>
                  <option value="happy">快乐</option>
                  <option value="sad">悲伤</option>
                  <option value="angry">愤怒</option>
                  <option value="fearful">恐惧</option>
                  <option value="disgusted">厌恶</option>
                  <option value="surprised">惊讶</option>
                </select>
              </div>

              {/* 生成按钮 */}
              <button
                onClick={handleGenerateSpeech}
                disabled={speechState.status === SpeechGenerationStatus.GENERATING}
                className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {speechState.status === SpeechGenerationStatus.GENERATING ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    生成中...
                  </>
                ) : (
                  <>
                    <Volume2 className="w-4 h-4" />
                    生成语音
                  </>
                )}
              </button>

              {/* 生成状态显示 */}
              {speechState.status !== SpeechGenerationStatus.IDLE && (
                <div className="space-y-3">
                  <div className="flex items-center gap-2 text-sm">
                    {speechState.status === SpeechGenerationStatus.SUCCESS && (
                      <>
                        <CheckCircle className="w-4 h-4 text-green-600" />
                        <span className="text-green-600">生成成功</span>
                      </>
                    )}
                    {speechState.status === SpeechGenerationStatus.ERROR && (
                      <>
                        <XCircle className="w-4 h-4 text-red-600" />
                        <span className="text-red-600">生成失败: {speechState.error}</span>
                      </>
                    )}
                    {speechState.status === SpeechGenerationStatus.GENERATING && (
                      <>
                        <Loader2 className="w-4 h-4 animate-spin text-green-600" />
                        <span className="text-green-600">{speechState.progress}</span>
                      </>
                    )}
                  </div>

                  {/* 音频播放器 */}
                  {speechState.result?.data && (
                    <div className="p-4 bg-gray-50 rounded-lg">
                      <div className="flex items-center justify-between mb-3">
                        <span className="text-sm font-medium text-gray-700">生成的语音</span>
                        <button
                          onClick={() => {
                            // 下载音频文件
                            const link = document.createElement('a');
                            link.href = speechState.result!.data!;
                            link.download = 'generated_speech.wav';
                            link.click();
                          }}
                          className="flex items-center gap-1 px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
                        >
                          <Download className="w-3 h-3" />
                          下载
                        </button>
                      </div>
                      
                      <audio
                        controls
                        src={speechState.result.data}
                        className="w-full"
                      >
                        您的浏览器不支持音频播放
                      </audio>
                    </div>
                  )}
                </div>
              )}

              {/* 语音生成历史记录 */}
              <div className="mt-8">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold text-gray-900">语音生成历史</h3>
                  <button
                    onClick={loadSpeechRecords}
                    disabled={loadingRecords}
                    className="flex items-center gap-2 px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50 transition-colors"
                  >
                    <RefreshCw className={`w-3 h-3 ${loadingRecords ? 'animate-spin' : ''}`} />
                    刷新
                  </button>
                </div>

                {loadingRecords ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
                    <span className="ml-2 text-gray-500">加载中...</span>
                  </div>
                ) : speechRecords.length === 0 ? (
                  <div className="text-center py-8 text-gray-500">
                    <Music className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                    <p>暂无语音生成记录</p>
                  </div>
                ) : (
                  <div className="space-y-4 max-h-96 overflow-y-auto">
                    {speechRecords.map((record) => (
                      <div key={record.id} className="bg-white rounded-lg border border-gray-200 shadow-sm hover:shadow-md transition-shadow">
                        {/* 头部信息 */}
                        <div className="p-4 pb-3">
                          <div className="flex items-center justify-between mb-3">
                            <div className="flex items-center gap-2">
                              <span className={`px-2 py-1 text-xs font-medium rounded-full ${
                                record.status === SpeechGenerationRecordStatus.COMPLETED
                                  ? 'bg-green-100 text-green-800'
                                  : record.status === SpeechGenerationRecordStatus.FAILED
                                  ? 'bg-red-100 text-red-800'
                                  : record.status === SpeechGenerationRecordStatus.PROCESSING
                                  ? 'bg-blue-100 text-blue-800'
                                  : 'bg-gray-100 text-gray-800'
                              }`}>
                                {record.status === SpeechGenerationRecordStatus.COMPLETED && '已完成'}
                                {record.status === SpeechGenerationRecordStatus.FAILED && '失败'}
                                {record.status === SpeechGenerationRecordStatus.PROCESSING && '处理中'}
                                {record.status === SpeechGenerationRecordStatus.PENDING && '等待中'}
                                {record.status === SpeechGenerationRecordStatus.CANCELLED && '已取消'}
                              </span>
                              <span className="text-xs text-gray-500">
                                {new Date(record.created_at).toLocaleString()}
                              </span>
                            </div>

                            <div className="flex items-center gap-2">
                              {record.duration_ms && (
                                <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded">
                                  耗时: {record.duration_ms}ms
                                </span>
                              )}

                              {/* 删除按钮 */}
                              <button
                                onClick={() => deleteSpeechRecord(record.id)}
                                className="flex items-center justify-center w-6 h-6 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                                title="删除记录"
                              >
                                <Trash2 className="w-3 h-3" />
                              </button>
                            </div>
                          </div>

                          {/* 文本内容 */}
                          <div className="mb-3">
                            <p className="text-sm text-gray-900 leading-relaxed">
                              {record.text}
                            </p>
                          </div>

                          {/* 参数信息 */}
                          <div className="flex flex-wrap items-center gap-3 text-xs text-gray-600">
                            <div className="flex items-center gap-1">
                              <Music className="w-3 h-3" />
                              <span>{record.voice_name || record.voice_id}</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <span>语速:</span>
                              <span className="font-medium">{record.speed}x</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <Volume2 className="w-3 h-3" />
                              <span>{record.volume}</span>
                            </div>
                            {record.emotion && (
                              <div className="flex items-center gap-1">
                                <span>情感:</span>
                                <span className="font-medium">{record.emotion}</span>
                              </div>
                            )}
                          </div>

                          {/* 错误信息 */}
                          {record.error_message && (
                            <div className="mt-3 p-2 bg-red-50 border border-red-200 rounded text-xs text-red-600">
                              <div className="flex items-center gap-1">
                                <XCircle className="w-3 h-3" />
                                <span>错误: {record.error_message}</span>
                              </div>
                            </div>
                          )}
                        </div>

                        {/* 音频播放区域 */}
                        {record.audio_url && (
                          <div className="px-4 pb-4">
                            <div className="bg-gray-50 rounded-lg p-3 border-t border-gray-100">
                              <div className="flex items-center justify-between gap-3">
                                <div className="flex items-center gap-2 text-xs text-gray-600">
                                  <FileAudio className="w-4 h-4" />
                                  <span>生成的音频</span>
                                </div>

                                <div className="flex items-center gap-2">
                                  <audio
                                    controls
                                    src={record.audio_url}
                                    className="h-8"
                                    style={{ width: '200px' }}
                                    preload="metadata"
                                  >
                                    您的浏览器不支持音频播放
                                  </audio>

                                  <button
                                    onClick={() => {
                                      const link = document.createElement('a');
                                      link.href = record.audio_url!;
                                      link.download = `speech_${record.id}.wav`;
                                      link.click();
                                    }}
                                    className="flex items-center gap-1 px-3 py-1.5 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
                                    title="下载音频文件"
                                  >
                                    <Download className="w-3 h-3" />
                                    下载
                                  </button>
                                </div>
                              </div>
                            </div>
                          </div>
                        )}

                        {/* 如果没有音频URL但状态是完成，显示提示 */}
                        {!record.audio_url && record.status === SpeechGenerationRecordStatus.COMPLETED && (
                          <div className="px-4 pb-4">
                            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3 text-center">
                              <div className="flex items-center justify-center gap-2 text-xs text-yellow-700">
                                <XCircle className="w-4 h-4" />
                                <span>音频文件不可用</span>
                              </div>
                            </div>
                          </div>
                        )}

                        {/* 调试信息（仅开发环境） */}
                        {process.env.NODE_ENV === 'development' && (
                          <div className="px-4 pb-2">
                            <div className="text-xs text-gray-400 bg-gray-100 p-2 rounded">
                              调试: URL={record.audio_url ? '有' : '无'} | 状态={record.status}
                            </div>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VoiceCloneTool;
