import React, { useState, useEffect, useCallback } from 'react';
import {
  Download,
  Trash2,
  RefreshCw,
  CheckCircle,
  XCircle,
  Loader2,
  AlertCircle,
  Image,
  Music,
  Video,
  Plus
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { useNotifications } from '../../components/NotificationSystem';
import HedraLipSyncModal from '../../components/HedraLipSyncModal';
import { getImageSrc } from '../../utils/imagePathUtils';

interface HedraLipSyncRecord {
  id: string;
  task_id?: string;
  image_path: string;
  image_url?: string;
  audio_path: string;
  audio_url?: string;
  prompt?: string;
  status: 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled';
  progress: number;
  result_video_url?: string;
  result_video_path?: string;
  error_message?: string;
  created_at: string;
  started_at?: string;
  completed_at?: string;
  duration_ms?: number;
  file_size_bytes?: number;
  video_duration_seconds?: number;
}

interface HedraLipSyncStatistics {
  total: number;
  completed: number;
  processing: number;
  failed: number;
}

/**
 * Hedra 口型合成记录列表页面
 */
const HedraLipSyncRecords: React.FC = () => {
  const { addNotification } = useNotifications();
  const [records, setRecords] = useState<HedraLipSyncRecord[]>([]);
  const [statistics, setStatistics] = useState<HedraLipSyncStatistics | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedRecords, setSelectedRecords] = useState<Set<string>>(new Set());
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 加载记录列表
  const loadRecords = useCallback(async () => {
    try {
      setLoading(true);
      const data = await invoke<HedraLipSyncRecord[]>('get_all_hedra_lipsync_records', { limit: 100 });
      setRecords(data);
    } catch (error) {
      console.error('加载记录失败:', error);
      addNotification({
        type: 'error',
        title: '加载失败',
        message: '无法加载Hedra合成记录'
      });
    } finally {
      setLoading(false);
    }
  }, [addNotification]);

  // 加载统计信息
  const loadStatistics = useCallback(async () => {
    try {
      const stats = await invoke<HedraLipSyncStatistics>('get_hedra_lipsync_statistics');
      setStatistics(stats);
    } catch (error) {
      console.error('加载统计信息失败:', error);
    }
  }, []);

  // 初始化加载
  useEffect(() => {
    loadRecords();
    loadStatistics();
  }, [loadRecords, loadStatistics]);

  // 监听 Hedra 任务进度事件
  useEffect(() => {
    const unlisten = listen('hedra-task-progress', (event: any) => {
      console.log('收到 Hedra 任务进度事件:', event.payload);

      const { record_id, status, progress, result_video_url, error_message } = event.payload;

      // 更新对应记录的状态
      setRecords(prevRecords =>
        prevRecords.map(record => {
          if (record.id === record_id) {
            return {
              ...record,
              status: status as HedraLipSyncRecord['status'],
              progress: progress || record.progress,
              result_video_url: result_video_url || record.result_video_url,
              error_message: error_message || record.error_message
            };
          }
          return record;
        })
      );

      // 显示通知
      if (status === 'completed') {
        addNotification({
          type: 'success',
          title: 'Hedra 任务完成',
          message: '口型合成视频已生成完成'
        });
      } else if (status === 'failed') {
        addNotification({
          type: 'error',
          title: 'Hedra 任务失败',
          message: error_message || '口型合成任务执行失败'
        });
      }
    });

    return () => {
      unlisten.then(fn => fn());
    };
  }, [addNotification]);

  // 删除记录
  const handleDelete = useCallback(async (id: string) => {
    try {
      await invoke('delete_hedra_lipsync_record', { id });
      addNotification({
        type: 'success',
        title: '删除成功',
        message: '记录已删除'
      });
      loadRecords();
      loadStatistics();
    } catch (error) {
      console.error('删除记录失败:', error);
      addNotification({
        type: 'error',
        title: '删除失败',
        message: '无法删除记录'
      });
    }
  }, [addNotification, loadRecords, loadStatistics]);

  // 批量删除
  const handleBatchDelete = useCallback(async () => {
    if (selectedRecords.size === 0) {
      addNotification({
        type: 'warning',
        title: '未选择记录',
        message: '请先选择要删除的记录'
      });
      return;
    }

    try {
      const ids = Array.from(selectedRecords);
      await invoke('batch_delete_hedra_lipsync_records', { request: { ids } });
      addNotification({
        type: 'success',
        title: '批量删除成功',
        message: `已删除 ${selectedRecords.size} 条记录`
      });
      setSelectedRecords(new Set());
      loadRecords();
      loadStatistics();
    } catch (error) {
      console.error('批量删除失败:', error);
      addNotification({
        type: 'error',
        title: '批量删除失败',
        message: '无法删除选中的记录'
      });
    }
  }, [selectedRecords, addNotification, loadRecords, loadStatistics]);

  // 批量下载
  const handleBatchDownload = useCallback(async () => {
    if (selectedRecords.size === 0) {
      addNotification({
        type: 'warning',
        title: '未选择记录',
        message: '请先选择要下载的记录'
      });
      return;
    }

    const selectedRecordsList = records.filter(record => selectedRecords.has(record.id));
    const downloadableRecords = selectedRecordsList.filter(record => record.result_video_url);

    if (downloadableRecords.length === 0) {
      addNotification({
        type: 'warning',
        title: '无可下载文件',
        message: '选中的记录中没有可下载的视频文件'
      });
      return;
    }

    try {
      let successCount = 0;
      let failCount = 0;

      for (const record of downloadableRecords) {
        try {
          // 创建下载链接
          const link = document.createElement('a');
          link.href = record.result_video_url!;
          link.download = `hedra_video_${record.id}_${new Date().getTime()}.mp4`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          successCount++;
        } catch (error) {
          console.error(`下载失败 ${record.id}:`, error);
          failCount++;
        }
        // 添加小延迟避免同时下载太多文件
        await new Promise(resolve => setTimeout(resolve, 500));
      }

      addNotification({
        type: successCount > 0 ? 'success' : 'error',
        title: '批量下载完成',
        message: `成功下载 ${successCount} 个文件${failCount > 0 ? `，失败 ${failCount} 个` : ''}`
      });
    } catch (error) {
      console.error('批量下载失败:', error);
      addNotification({
        type: 'error',
        title: '批量下载失败',
        message: '批量下载过程中发生错误'
      });
    }
  }, [selectedRecords, records, addNotification]);

  // 处理Modal任务创建成功
  const handleTaskCreated = useCallback((recordId: string) => {
    console.log('新任务创建成功:', recordId);
    // 刷新记录列表和统计信息
    loadRecords();
    loadStatistics();
    // 关闭Modal
    setIsModalOpen(false);

    addNotification({
      type: 'success',
      title: '任务创建成功',
      message: '新的口型合成任务已创建，请在列表中查看进度'
    });
  }, [loadRecords, loadStatistics, addNotification]);

  // 下载视频
  const handleDownload = useCallback(async (record: HedraLipSyncRecord) => {
    if (!record.result_video_url) {
      addNotification({
        type: 'warning',
        title: '无法下载',
        message: '该记录没有可下载的视频'
      });
      return;
    }

    try {
      // 创建下载链接
      const link = document.createElement('a');
      link.href = record.result_video_url;
      link.download = `hedra_${record.id}.mp4`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      addNotification({
        type: 'success',
        title: '开始下载',
        message: '视频下载已开始'
      });
    } catch (error) {
      console.error('下载失败:', error);
      addNotification({
        type: 'error',
        title: '下载失败',
        message: '无法下载视频文件'
      });
    }
  }, [addNotification]);

  // 预览音频
  const handlePreviewAudio = useCallback(async (audioPath: string) => {
    try {
      // 使用Tauri的convertFileSrc来转换文件路径为可访问的URL
      const { convertFileSrc } = await import('@tauri-apps/api/core');
      const audioUrl = convertFileSrc(audioPath);

      // 创建音频元素并播放
      const audio = new Audio(audioUrl);
      audio.play().catch(error => {
        console.error('播放音频失败:', error);
        addNotification({
          type: 'error',
          title: '播放失败',
          message: '无法播放音频文件'
        });
      });
    } catch (error) {
      console.error('预览音频失败:', error);
      addNotification({
        type: 'error',
        title: '预览失败',
        message: '无法预览音频文件'
      });
    }
  }, [addNotification]);

  // 状态图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'processing':
        return <Loader2 className="w-4 h-4 text-blue-500 animate-spin" />;
      case 'failed':
        return <XCircle className="w-4 h-4 text-red-500" />;
      case 'cancelled':
        return <XCircle className="w-4 h-4 text-gray-500" />;
      default:
        return <AlertCircle className="w-4 h-4 text-yellow-500" />;
    }
  };

  // 状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending':
        return '等待中';
      case 'processing':
        return '处理中';
      case 'completed':
        return '已完成';
      case 'failed':
        return '失败';
      case 'cancelled':
        return '已取消';
      default:
        return '未知';
    }
  };

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

  // 过滤记录
  const filteredRecords = records.filter(record => {
    if (statusFilter === 'all') return true;
    return record.status === statusFilter;
  });

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题和统计 */}
      <div className="flex justify-between items-start">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Hedra 口型合成记录</h1>
          <p className="text-gray-600 mt-1">管理和查看所有的口型合成任务记录</p>
        </div>
        
        {statistics && (
          <div className="grid grid-cols-4 gap-4 text-center">
            <div className="bg-blue-50 rounded-lg p-3">
              <div className="text-2xl font-bold text-blue-600">{statistics.total}</div>
              <div className="text-sm text-blue-600">总计</div>
            </div>
            <div className="bg-green-50 rounded-lg p-3">
              <div className="text-2xl font-bold text-green-600">{statistics.completed}</div>
              <div className="text-sm text-green-600">已完成</div>
            </div>
            <div className="bg-yellow-50 rounded-lg p-3">
              <div className="text-2xl font-bold text-yellow-600">{statistics.processing}</div>
              <div className="text-sm text-yellow-600">处理中</div>
            </div>
            <div className="bg-red-50 rounded-lg p-3">
              <div className="text-2xl font-bold text-red-600">{statistics.failed}</div>
              <div className="text-sm text-red-600">失败</div>
            </div>
          </div>
        )}
      </div>

      {/* 操作栏 */}
      <div className="flex justify-between items-center">
        <div className="flex items-center gap-4">
          {/* 状态筛选 */}
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            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="pending">等待中</option>
            <option value="processing">处理中</option>
            <option value="completed">已完成</option>
            <option value="failed">失败</option>
            <option value="cancelled">已取消</option>
          </select>

          {/* 批量操作 */}
          {selectedRecords.size > 0 && (
            <div className="flex items-center gap-2">
              <button
                onClick={handleBatchDownload}
                className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
              >
                <Download className="w-4 h-4" />
                批量下载 ({selectedRecords.size})
              </button>
              <button
                onClick={handleBatchDelete}
                className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
              >
                <Trash2 className="w-4 h-4" />
                删除选中 ({selectedRecords.size})
              </button>
            </div>
          )}
        </div>

        <div className="flex items-center gap-3">
          <button
            onClick={() => setIsModalOpen(true)}
            className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            <Plus className="w-4 h-4" />
            创建新任务
          </button>
          <button
            onClick={() => {
              loadRecords();
              loadStatistics();
            }}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <RefreshCw className="w-4 h-4" />
            刷新
          </button>
        </div>
      </div>

      {/* 记录列表 */}
      {loading ? (
        <div className="flex justify-center items-center py-12">
          <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
          <span className="ml-2 text-gray-600">加载中...</span>
        </div>
      ) : filteredRecords.length === 0 ? (
        <div className="text-center py-12">
          <Video className="w-16 h-16 mx-auto text-gray-400 mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">暂无记录</h3>
          <p className="text-gray-600">还没有任何口型合成记录</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-6">
          {filteredRecords.map((record) => (
            <div key={record.id} className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow">
              {/* 卡片头部：选择框和状态 */}
              <div className="p-4">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={selectedRecords.has(record.id)}
                      onChange={(e) => {
                        const newSelected = new Set(selectedRecords);
                        if (e.target.checked) {
                          newSelected.add(record.id);
                        } else {
                          newSelected.delete(record.id);
                        }
                        setSelectedRecords(newSelected);
                      }}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                    {record.task_id && (
                      <span className="text-xs text-gray-500">ID: {record.task_id.slice(-8)}</span>
                    )}
                  </div>
                  <div className="flex items-center gap-1">
                    {getStatusIcon(record.status)}
                    <span className="text-xs font-medium text-gray-700">
                      {getStatusText(record.status)}
                    </span>
                  </div>
                </div>

                {/* 进度条 */}
                {record.status === 'processing' && record.progress > 0 && (
                  <div className="space-y-1 mb-3">
                    <div className="flex justify-between text-xs text-gray-500">
                      <span>进度</span>
                      <span>{Math.round(record.progress * 100)}%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-1.5">
                      <div
                        className="bg-blue-600 h-1.5 rounded-full transition-all duration-300"
                        style={{ width: `${record.progress * 100}%` }}
                      />
                    </div>
                  </div>
                )}

                {/* 图片和内容区域 */}
                <div className="flex gap-3">
                  {/* 左侧：缩小的图片 */}
                  <div className="flex-shrink-0">
                    <div className="relative">
                      <img
                        src={getImageSrc(record.image_path)}
                        alt="原始图片"
                        className="w-16 h-16 object-cover rounded-lg cursor-pointer hover:opacity-80 transition-opacity"
                        onError={(e) => {
                          // 如果图片加载失败，显示占位图
                          e.currentTarget.style.display = 'none';
                          e.currentTarget.nextElementSibling?.classList.remove('hidden');
                        }}
                      />
                      <div className="hidden w-16 h-16 flex items-center justify-center bg-gray-100 rounded-lg">
                        <Image className="w-6 h-6 text-gray-400" />
                      </div>
                    </div>
                  </div>

                  {/* 右侧：提示词和音频 */}
                  <div className="flex-1 min-w-0 space-y-2">
                    {/* 提示词 */}
                    {record.prompt && (
                      <div className="text-xs text-gray-800 line-clamp-2" title={record.prompt}>
                        {record.prompt}
                      </div>
                    )}

                    {/* 音频播放 */}
                    <div className="flex items-center gap-2">
                      <Music className="w-3 h-3 text-green-500 flex-shrink-0" />
                      <button
                        onClick={() => handlePreviewAudio(record.audio_path)}
                        className="text-xs text-green-600 hover:text-green-800 truncate"
                        title={record.audio_path}
                      >
                        {record.audio_path.split(/[/\\]/).pop()}
                      </button>
                    </div>
                  </div>
                </div>
              </div>



              {/* 视频预览区域 - 总是显示，用于调试 */}
              {record.status === 'completed' && (
                <div className="border-t border-gray-200">
                  <div className="aspect-video bg-black">
                    {(record.result_video_url || record.result_video_path) ? (
                      <video
                        controls
                        className="w-full h-full object-contain"
                        preload="metadata"
                        onError={(e) => {
                          console.error('视频加载失败:', e);
                          console.log('视频源:', record.result_video_url || record.result_video_path);
                        }}
                      >
                        <source src={getImageSrc(record.result_video_url || record.result_video_path!)} type="video/mp4" />
                        您的浏览器不支持视频播放
                      </video>
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-white">
                        <div className="text-center">
                          <Video className="w-12 h-12 mx-auto mb-2 text-gray-400" />
                          <p className="text-sm text-gray-400">视频URL为空</p>
                          <p className="text-xs text-gray-500 mt-1">任务已完成但未获取到视频链接</p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* 创建时间和操作按钮 - 放在最底部 */}
              <div className="px-4 py-2 border-t border-gray-100 bg-gray-50 flex items-center justify-between">
                <div className="text-xs text-gray-500">
                  {formatTime(record.created_at)}
                </div>
                <div className="flex gap-2">
                  {record.result_video_url && (
                    <button
                      onClick={() => handleDownload(record)}
                      className="px-2 py-1 bg-green-600 text-white text-xs rounded hover:bg-green-700 transition-colors flex items-center gap-1"
                    >
                      <Download className="w-3 h-3" />
                      下载
                    </button>
                  )}
                  <button
                    onClick={() => handleDelete(record.id)}
                    className="px-2 py-1 bg-red-600 text-white text-xs rounded hover:bg-red-700 transition-colors flex items-center gap-1"
                  >
                    <Trash2 className="w-3 h-3" />
                    删除
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Hedra 口型合成Modal */}
      <HedraLipSyncModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onTaskCreated={handleTaskCreated}
      />
    </div>
  );
};

export default HedraLipSyncRecords;
