import React, { useState, useCallback, useEffect } from 'react';
import {
  Search,
  Plus,
  Play,
  Pause,
  Download,
  Trash2,
  RefreshCw,
  Calendar,
  Clock,
  Filter,
  Music,
  Loader2,
  Volume2,
  Mic,
  CheckCircle,
  XCircle,
  AlertCircle,
  FolderDown,
  Square,
  CheckSquare
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { useNotifications } from '../../components/NotificationSystem';
import { VoiceCloneModal } from '../../components/VoiceCloneModal';
import { SpeechGenerationModal } from '../../components/SpeechGenerationModal';
import {
  SpeechGenerationRecord,
  SpeechGenerationRecordStatus
} from '../../types/voiceClone';

/**
 * 语音生成历史页面
 * 展示语音生成记录列表，支持搜索、筛选、播放等功能
 */
const VoiceGenerationHistory: React.FC = () => {
  const { addNotification } = useNotifications();

  // ============= 状态管理 =============
  
  // 记录列表
  const [records, setRecords] = useState<SpeechGenerationRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<SpeechGenerationRecordStatus | 'all'>('all');
  
  // 音频播放状态
  const [playingRecordId, setPlayingRecordId] = useState<string | null>(null);
  const [audioElement, setAudioElement] = useState<HTMLAudioElement | null>(null);

  // Modal状态
  const [showVoiceCloneModal, setShowVoiceCloneModal] = useState(false);
  const [showSpeechGenerationModal, setShowSpeechGenerationModal] = useState(false);

  // 批量选择状态
  const [selectedRecords, setSelectedRecords] = useState<Set<string>>(new Set());
  const [isSelectionMode, setIsSelectionMode] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);

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

  // 加载语音生成记录
  const loadRecords = useCallback(async () => {
    setLoading(true);
    try {
      const allRecords = await invoke<SpeechGenerationRecord[]>('get_speech_generation_records', {
        limit: 100 // 限制最近100条记录
      });



      // 标准化记录状态
      const normalizedRecords = allRecords.map(record => ({
        ...record,
        status: normalizeStatus(record.status)
      }));

      // 根据搜索和筛选条件过滤记录
      let filteredRecords = normalizedRecords;

      if (searchText.trim()) {
        filteredRecords = filteredRecords.filter(record =>
          record.text.toLowerCase().includes(searchText.toLowerCase()) ||
          (record.voice_name && record.voice_name.toLowerCase().includes(searchText.toLowerCase())) ||
          record.voice_id.toLowerCase().includes(searchText.toLowerCase())
        );
      }

      if (statusFilter !== 'all') {
        const normalizedFilter = normalizeStatus(statusFilter);
        filteredRecords = filteredRecords.filter(record => {
          return record.status === normalizedFilter;
        });
      }

      setRecords(filteredRecords);
    } catch (error) {
      console.error('加载语音生成记录失败:', error);
      addNotification({
        type: 'error',
        title: '加载失败',
        message: `加载语音生成记录失败: ${error}`
      });
    } finally {
      setLoading(false);
    }
  }, [searchText, statusFilter, addNotification]);

  // 删除记录
  const handleDeleteRecord = useCallback(async (recordId: string) => {
    try {
      await invoke('delete_speech_generation_record', { recordId });
      setRecords(prev => prev.filter(r => r.id !== recordId));
      addNotification({
        type: 'success',
        title: '删除成功',
        message: '语音生成记录已删除'
      });
    } catch (error) {
      console.error('删除记录失败:', error);
      addNotification({
        type: 'error',
        title: '删除失败',
        message: `删除记录失败: ${error}`
      });
    }
  }, [addNotification]);

  // 播放/暂停音频
  const handlePlayPause = useCallback((record: SpeechGenerationRecord) => {
    if (!record.audio_url && !record.local_file_path) {
      addNotification({
        type: 'warning',
        title: '无法播放',
        message: '该记录没有可播放的音频文件'
      });
      return;
    }

    const audioUrl = record.local_file_path || record.audio_url;
    
    if (playingRecordId === record.id) {
      // 暂停当前播放
      if (audioElement) {
        audioElement.pause();
        setPlayingRecordId(null);
      }
    } else {
      // 停止之前的播放
      if (audioElement) {
        audioElement.pause();
      }
      
      // 开始新的播放
      const audio = new Audio(audioUrl);
      audio.onended = () => setPlayingRecordId(null);
      audio.onerror = () => {
        addNotification({
          type: 'error',
          title: '播放失败',
          message: '音频文件播放失败'
        });
        setPlayingRecordId(null);
      };
      
      audio.play().then(() => {
        setPlayingRecordId(record.id);
        setAudioElement(audio);
      }).catch(error => {
        console.error('播放失败:', error);
        addNotification({
          type: 'error',
          title: '播放失败',
          message: '音频文件播放失败'
        });
      });
    }
  }, [playingRecordId, audioElement, addNotification]);

  // 下载音频文件到指定目录
  const handleDownloadToDirectory = useCallback(async (record: SpeechGenerationRecord) => {
    if (!record.audio_url && !record.local_file_path) {
      addNotification({
        type: 'warning',
        title: '无法下载',
        message: '该记录没有可下载的音频文件'
      });
      return;
    }

    try {
      // 选择下载目录
      const selectedDirectory = await invoke<string | null>('select_directory_with_options', {
        title: '选择下载目录',
        defaultDirectory: null
      });

      if (!selectedDirectory) {
        return; // 用户取消选择
      }

      const audioUrl = record.local_file_path || record.audio_url;

      // 生成文件名
      const text = record.text.substring(0, 30).replace(/[^\w\s-]/g, '').trim().replace(/\s+/g, '_');
      const filename = text ? `${text}_${record.id}.wav` : `speech_${record.id}.wav`;

      // 下载文件
      const savedPath = await invoke<string>('download_audio_to_directory', {
        recordId: record.id,
        audioUrl: audioUrl!,
        directoryPath: selectedDirectory,
        filename
      });

      addNotification({
        type: 'success',
        title: '下载成功',
        message: `文件已保存到: ${savedPath}`
      });
    } catch (error) {
      console.error('下载失败:', error);
      addNotification({
        type: 'error',
        title: '下载失败',
        message: `下载失败: ${error}`
      });
    }
  }, [addNotification]);

  // 批量下载到指定目录
  const handleBatchDownload = useCallback(async () => {
    const downloadableRecords = records.filter(record =>
      selectedRecords.has(record.id) &&
      (record.audio_url || record.local_file_path) &&
      record.status === SpeechGenerationRecordStatus.COMPLETED
    );

    if (downloadableRecords.length === 0) {
      addNotification({
        type: 'warning',
        title: '无可下载文件',
        message: '请选择至少一个有音频文件的已完成记录'
      });
      return;
    }

    try {
      // 选择下载目录
      const selectedDirectory = await invoke<string | null>('select_directory_with_options', {
        title: '选择批量下载目录',
        defaultDirectory: null
      });

      if (!selectedDirectory) {
        return; // 用户取消选择
      }

      setIsDownloading(true);

      // 批量下载
      const downloadedFiles = await invoke<string[]>('batch_download_audio_to_directory', {
        records: downloadableRecords,
        directoryPath: selectedDirectory
      });

      addNotification({
        type: 'success',
        title: '批量下载完成',
        message: `成功下载 ${downloadedFiles.length} 个文件到: ${selectedDirectory}`
      });

      // 清空选择
      setSelectedRecords(new Set());
      setIsSelectionMode(false);
    } catch (error) {
      console.error('批量下载失败:', error);
      addNotification({
        type: 'error',
        title: '批量下载失败',
        message: `批量下载失败: ${error}`
      });
    } finally {
      setIsDownloading(false);
    }
  }, [records, selectedRecords, addNotification]);

  // 兼容旧的下载方法（浏览器直接下载）
  const handleQuickDownload = useCallback((record: SpeechGenerationRecord) => {
    if (!record.audio_url && !record.local_file_path) {
      addNotification({
        type: 'warning',
        title: '无法下载',
        message: '该记录没有可下载的音频文件'
      });
      return;
    }

    const audioUrl = record.local_file_path || record.audio_url;
    const link = document.createElement('a');
    link.href = audioUrl!;
    link.download = `speech_${record.id}.wav`;
    link.click();
  }, [addNotification]);

  // ============= 批量选择处理函数 =============

  // 切换选择模式
  const toggleSelectionMode = useCallback(() => {
    setIsSelectionMode(!isSelectionMode);
    if (isSelectionMode) {
      setSelectedRecords(new Set());
    }
  }, [isSelectionMode]);

  // 切换单个记录选择
  const toggleRecordSelection = useCallback((recordId: string) => {
    setSelectedRecords(prev => {
      const newSet = new Set(prev);
      if (newSet.has(recordId)) {
        newSet.delete(recordId);
      } else {
        newSet.add(recordId);
      }
      return newSet;
    });
  }, []);

  // 全选/取消全选
  const toggleSelectAll = useCallback(() => {
    const downloadableRecords = records.filter(record =>
      (record.audio_url || record.local_file_path) &&
      record.status === SpeechGenerationRecordStatus.COMPLETED
    );

    const allSelected = downloadableRecords.every(record => selectedRecords.has(record.id));

    if (allSelected) {
      setSelectedRecords(new Set());
    } else {
      setSelectedRecords(new Set(downloadableRecords.map(record => record.id)));
    }
  }, [records, selectedRecords]);

  // ============= Modal处理函数 =============

  // 声音克隆成功回调
  const handleVoiceCloneSuccess = useCallback((voiceId: string) => {
    console.log('声音克隆成功，音色ID:', voiceId);
    // 刷新记录列表
    loadRecords();
  }, [loadRecords]);

  // 语音合成成功回调
  const handleSpeechGenerationSuccess = useCallback((audioUrl: string) => {
    console.log('语音合成成功，音频URL:', audioUrl);
    // 刷新记录列表
    loadRecords();
  }, [loadRecords]);

  // ============= 生命周期 =============

  useEffect(() => {
    loadRecords();
  }, [loadRecords]);

  // 清理音频元素
  useEffect(() => {
    return () => {
      if (audioElement) {
        audioElement.pause();
      }
    };
  }, [audioElement]);

  // ============= 辅助函数 =============

  // 状态转换函数 - 确保类型安全
  const normalizeStatus = (status: any): SpeechGenerationRecordStatus => {
    // 如果已经是正确的枚举值，直接返回
    if (Object.values(SpeechGenerationRecordStatus).includes(status)) {
      return status as SpeechGenerationRecordStatus;
    }

    // 如果是字符串，尝试转换
    if (typeof status === 'string') {
      const normalizedStatus = status.toLowerCase();
      switch (normalizedStatus) {
        case 'pending':
          return SpeechGenerationRecordStatus.PENDING;
        case 'processing':
          return SpeechGenerationRecordStatus.PROCESSING;
        case 'completed':
          return SpeechGenerationRecordStatus.COMPLETED;
        case 'failed':
          return SpeechGenerationRecordStatus.FAILED;
        case 'cancelled':
          return SpeechGenerationRecordStatus.CANCELLED;
        default:
          console.warn('⚠️ 未知状态字符串:', status);
          return SpeechGenerationRecordStatus.PENDING;
      }
    }

    console.warn('⚠️ 无法识别的状态类型:', status, typeof status);
    return SpeechGenerationRecordStatus.PENDING;
  };

  // 格式化时间
  const formatTime = (timeStr: string) => {
    const date = new Date(timeStr);
    return date.toLocaleString('zh-CN');
  };

  // 格式化持续时间
  const formatDuration = (ms?: number) => {
    if (!ms) return '-';
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(1)}s`;
  };

  // 获取状态样式
  const getStatusStyle = (status: SpeechGenerationRecordStatus) => {
    switch (status) {
      case SpeechGenerationRecordStatus.COMPLETED:
        return 'bg-green-100 text-green-800 border-green-200';
      case SpeechGenerationRecordStatus.FAILED:
        return 'bg-red-100 text-red-800 border-red-200';
      case SpeechGenerationRecordStatus.PROCESSING:
        return 'bg-blue-100 text-blue-800 border-blue-200';
      case SpeechGenerationRecordStatus.PENDING:
        return 'bg-yellow-100 text-yellow-800 border-yellow-200';
      case SpeechGenerationRecordStatus.CANCELLED:
        return 'bg-gray-100 text-gray-800 border-gray-200';
      default:
        console.warn('⚠️ 未知状态，使用默认样式:', status);
        return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  // 获取状态图标
  const getStatusIcon = (status: SpeechGenerationRecordStatus) => {
    switch (status) {
      case SpeechGenerationRecordStatus.COMPLETED:
        return <CheckCircle className="w-3 h-3" />;
      case SpeechGenerationRecordStatus.FAILED:
        return <XCircle className="w-3 h-3" />;
      case SpeechGenerationRecordStatus.PROCESSING:
        return <Loader2 className="w-3 h-3 animate-spin" />;
      case SpeechGenerationRecordStatus.PENDING:
        return <Clock className="w-3 h-3" />;
      case SpeechGenerationRecordStatus.CANCELLED:
        return <XCircle className="w-3 h-3" />;
      default:
        return <AlertCircle className="w-3 h-3" />;
    }
  };

  // 获取状态文本
  const getStatusText = (status: SpeechGenerationRecordStatus) => {
    switch (status) {
      case SpeechGenerationRecordStatus.COMPLETED:
        return '已完成';
      case SpeechGenerationRecordStatus.FAILED:
        return '失败';
      case SpeechGenerationRecordStatus.PROCESSING:
        return '处理中';
      case SpeechGenerationRecordStatus.PENDING:
        return '待处理';
      case SpeechGenerationRecordStatus.CANCELLED:
        return '已取消';
      default:
        console.warn('⚠️ 未知状态，使用默认文本:', status);
        return '未知状态';
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 页面头部 */}
      <div className="bg-white border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="py-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 bg-gradient-to-br from-purple-500 to-pink-500 rounded-xl flex items-center justify-center shadow-sm">
                  <Volume2 className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">语音生成历史</h1>
                  <p className="text-sm text-gray-600 mt-1">管理和播放您的语音生成记录</p>
                </div>
              </div>
              
              <div className="flex items-center gap-3">
                {/* 批量操作按钮 */}
                {!isSelectionMode ? (
                  <>
                    <button
                      onClick={toggleSelectionMode}
                      className="flex items-center gap-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                    >
                      <CheckSquare className="w-4 h-4" />
                      批量下载
                    </button>
                    <button
                      onClick={() => setShowVoiceCloneModal(true)}
                      className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
                    >
                      <Mic className="w-4 h-4" />
                      声音克隆
                    </button>
                    <button
                      onClick={() => setShowSpeechGenerationModal(true)}
                      className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      <Plus className="w-4 h-4" />
                      语音合成
                    </button>
                  </>
                ) : (
                  <>
                    <button
                      onClick={toggleSelectAll}
                      className="flex items-center gap-2 px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      <CheckSquare className="w-4 h-4" />
                      {records.filter(r => (r.audio_url || r.local_file_path) && r.status === SpeechGenerationRecordStatus.COMPLETED).every(r => selectedRecords.has(r.id)) ? '取消全选' : '全选'}
                    </button>
                    <button
                      onClick={handleBatchDownload}
                      disabled={selectedRecords.size === 0 || isDownloading}
                      className="flex items-center gap-2 px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      {isDownloading ? (
                        <>
                          <Loader2 className="w-4 h-4 animate-spin" />
                          下载中...
                        </>
                      ) : (
                        <>
                          <FolderDown className="w-4 h-4" />
                          下载选中 ({selectedRecords.size})
                        </>
                      )}
                    </button>
                    <button
                      onClick={toggleSelectionMode}
                      className="flex items-center gap-2 px-3 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                    >
                      取消
                    </button>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 搜索和筛选栏 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="bg-white rounded-lg border border-gray-200 p-4 mb-6">
          <div className="flex flex-col sm:flex-row gap-4">
            {/* 搜索框 */}
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="搜索文本内容、音色名称或ID..."
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
            
            {/* 状态筛选 */}
            <div className="flex items-center gap-2">
              <Filter className="w-4 h-4 text-gray-400" />
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value as SpeechGenerationRecordStatus | 'all')}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="all">全部状态</option>
                <option value={SpeechGenerationRecordStatus.COMPLETED}>已完成</option>
                <option value={SpeechGenerationRecordStatus.PROCESSING}>处理中</option>
                <option value={SpeechGenerationRecordStatus.FAILED}>失败</option>
                <option value={SpeechGenerationRecordStatus.PENDING}>待处理</option>
              </select>
            </div>
            
            {/* 刷新按钮 */}
            <button
              onClick={loadRecords}
              disabled={loading}
              className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 disabled:opacity-50 transition-colors"
            >
              <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
              刷新
            </button>
          </div>
        </div>

        {/* 记录列表 */}
        <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
              <span className="ml-2 text-gray-500">加载中...</span>
            </div>
          ) : records.length === 0 ? (
            <div className="text-center py-12">
              <Music className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">暂无语音生成记录</h3>
              <p className="text-gray-500 mb-6">开始创建您的第一个语音生成记录</p>
              <div className="flex justify-center gap-3">
                <button
                  onClick={() => setShowVoiceCloneModal(true)}
                  className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
                >
                  <Mic className="w-4 h-4" />
                  声音克隆
                </button>
                <button
                  onClick={() => setShowSpeechGenerationModal(true)}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  <Plus className="w-4 h-4" />
                  语音合成
                </button>
              </div>
            </div>
          ) : (
            <div className="divide-y divide-gray-200">
              {records.map((record) => (
                <div key={record.id} className="p-6 hover:bg-gray-50 transition-colors">
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-4 flex-1 min-w-0">
                      {/* 选择框 */}
                      {isSelectionMode && (record.audio_url || record.local_file_path) && record.status === SpeechGenerationRecordStatus.COMPLETED && (
                        <button
                          onClick={() => toggleRecordSelection(record.id)}
                          className="mt-1 p-1 text-gray-400 hover:text-blue-600 transition-colors"
                        >
                          {selectedRecords.has(record.id) ? (
                            <CheckSquare className="w-5 h-5 text-blue-600" />
                          ) : (
                            <Square className="w-5 h-5" />
                          )}
                        </button>
                      )}

                      <div className="flex-1 min-w-0">
                        {/* 状态和基本信息 */}
                      <div className="flex items-center gap-3 mb-3">
                        <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium border ${getStatusStyle(record.status)}`}>
                          {getStatusIcon(record.status)}
                          {getStatusText(record.status)}
                        </span>
                        <span className="text-sm text-gray-500">
                          音色: {record.voice_name || record.voice_id}
                        </span>
                        {record.duration_ms && (
                          <span className="text-sm text-gray-500">
                            耗时: {formatDuration(record.duration_ms)}
                          </span>
                        )}
                      </div>

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

                      {/* 参数信息 */}
                      <div className="flex items-center gap-4 text-xs text-gray-500 mb-3">
                        <span>语速: {record.speed}x</span>
                        <span>音量: {record.volume}</span>
                        {record.emotion && <span>情感: {record.emotion}</span>}
                      </div>



                      {/* 时间信息 */}
                      <div className="flex items-center gap-4 text-xs text-gray-500">
                        <div className="flex items-center gap-1">
                          <Calendar className="w-3 h-3" />
                          <span>创建: {formatTime(record.created_at)}</span>
                        </div>
                        {record.completed_at && (
                          <div className="flex items-center gap-1">
                            <Clock className="w-3 h-3" />
                            <span>完成: {formatTime(record.completed_at)}</span>
                          </div>
                        )}
                      </div>

                      {/* 错误信息 */}
                      {record.error_message && (
                        <div className="mt-3 p-3 bg-red-50 border border-red-200 rounded-lg">
                          <p className="text-sm text-red-700">{record.error_message}</p>
                        </div>
                      )}
                      </div>
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex items-center gap-2 ml-4">
                      {/* 播放/暂停按钮 */}
                      {(record.audio_url || record.local_file_path) && record.status === SpeechGenerationRecordStatus.COMPLETED && (
                        <button
                          onClick={() => handlePlayPause(record)}
                          className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                          title={playingRecordId === record.id ? "暂停播放" : "播放音频"}
                        >
                          {playingRecordId === record.id ? (
                            <Pause className="w-4 h-4" />
                          ) : (
                            <Play className="w-4 h-4" />
                          )}
                        </button>
                      )}

                      {/* 下载按钮 */}
                      {(record.audio_url || record.local_file_path) && record.status === SpeechGenerationRecordStatus.COMPLETED && (
                        <div className="flex items-center gap-1">
                          {/* 快速下载（浏览器下载） */}
                          <button
                            onClick={() => handleQuickDownload(record)}
                            className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                            title="快速下载"
                          >
                            <Download className="w-4 h-4" />
                          </button>

                          {/* 下载到指定目录 */}
                          <button
                            onClick={() => handleDownloadToDirectory(record)}
                            className="p-2 text-gray-400 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors"
                            title="下载到指定目录"
                          >
                            <FolderDown className="w-4 h-4" />
                          </button>
                        </div>
                      )}

                      {/* 删除按钮 */}
                      <button
                        onClick={() => handleDeleteRecord(record.id)}
                        className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                        title="删除记录"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Modal组件 */}
      <VoiceCloneModal
        isOpen={showVoiceCloneModal}
        onClose={() => setShowVoiceCloneModal(false)}
        onSuccess={handleVoiceCloneSuccess}
      />

      <SpeechGenerationModal
        isOpen={showSpeechGenerationModal}
        onClose={() => setShowSpeechGenerationModal(false)}
        onSuccess={handleSpeechGenerationSuccess}
      />
    </div>
  );
};

export default VoiceGenerationHistory;
