import React, { useState, useCallback, useEffect } from 'react';
import {
  Video,
  Download,
  Trash2,
  RefreshCw,
  Plus,
  CheckCircle,
  XCircle,
  Clock,
  Loader2,
  Image as ImageIcon,
  Eye,
  X,
  FileVideo
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';
import { useNotifications } from '../../components/NotificationSystem';
import VideoPreviewModal from '../../components/VideoPreviewModal';

// 火山云视频生成相关类型定义
interface VideoGenerationRecord {
  id: string;
  name: string;
  image_url?: string;
  audio_url?: string;
  prompt?: string;
  negative_prompt?: string;
  duration: number;
  fps: number;
  resolution: string;
  style?: string;
  motion_strength: number;
  status: 'Pending' | 'Processing' | 'Completed' | 'Failed';
  progress: number;
  result_video_url?: string;
  result_thumbnail_url?: string;
  error_message?: string;
  vol_task_id?: string;
  project_id?: string;
  created_at: string;
  updated_at: string;
}

interface CreateVideoGenerationRequest {
  name: string;
  image_url?: string;
  audio_url?: string; // 实际上是驱动视频URL，复用audio_url字段
  // 注意：根据火山云API文档，需要图片和驱动视频两个文件
}

/**
 * 火山云视频生成工具
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
const VideoGenerationTool: React.FC = () => {
  const { addNotification } = useNotifications();

  // ============= 状态管理 =============
  
  // 视频生成记录列表
  const [records, setRecords] = useState<VideoGenerationRecord[]>([]);
  const [isLoadingRecords, setIsLoadingRecords] = useState(false);
  const [selectedRecords, setSelectedRecords] = useState<string[]>([]);

  // 创建任务表单
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [formData, setFormData] = useState<CreateVideoGenerationRequest>({
    name: '',
    image_url: '',
    audio_url: '', // 驱动视频URL
  });

  // 视频预览相关状态
  const [previewVideoUrl, setPreviewVideoUrl] = useState<string | null>(null);
  const [previewVideoTitle, setPreviewVideoTitle] = useState<string>('');

  // ============= 数据加载 =============
  
  // 加载视频生成记录
  const loadRecords = useCallback(async () => {
    try {
      setIsLoadingRecords(true);
      const result = await invoke<VideoGenerationRecord[]>('get_volcano_video_generations', {
        query: null
      });
      setRecords(result);
    } catch (error) {
      console.error('加载视频生成记录失败:', error);
      addNotification({
        type: 'error',
        title: '加载失败',
        message: '加载视频生成记录失败'
      });
    } finally {
      setIsLoadingRecords(false);
    }
  }, [addNotification]);

  // 组件挂载时加载数据
  useEffect(() => {
    loadRecords();
  }, [loadRecords]);

  // ============= 文件选择 =============
  
  // 选择图片文件
  const selectImageFile = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [
          {
            name: '图片文件',
            extensions: ['jpg', 'jpeg', 'png', 'webp', 'bmp'],
          },
        ],
      });

      if (selected && typeof selected === 'string') {
        setFormData(prev => ({ ...prev, image_url: selected }));
      }
    } catch (error) {
      console.error('选择图片文件失败:', error);
      addNotification({
        type: 'error',
        title: '文件选择失败',
        message: '选择图片文件失败'
      });
    }
  }, [addNotification]);

  // 选择驱动视频文件
  const selectAudioFile = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [
          {
            name: '视频文件',
            extensions: ['mp4', 'avi', 'mov', 'mkv', 'webm'],
          },
        ],
      });

      if (selected && typeof selected === 'string') {
        setFormData(prev => ({ ...prev, audio_url: selected }));
      }
    } catch (error) {
      console.error('选择驱动视频文件失败:', error);
      addNotification({
        type: 'error',
        title: '文件选择失败',
        message: '选择驱动视频文件失败'
      });
    }
  }, [addNotification]);

  // ============= 任务操作 =============
  
  // 创建视频生成任务
  const createVideoGeneration = useCallback(async () => {
    if (!formData.name.trim()) {
      addNotification({
        type: 'warning',
        title: '输入错误',
        message: '请输入任务名称'
      });
      return;
    }

    if (!formData.image_url) {
      addNotification({
        type: 'warning',
        title: '输入错误',
        message: '请选择图片文件'
      });
      return;
    }

    if (!formData.audio_url) {
      addNotification({
        type: 'warning',
        title: '输入错误',
        message: '请选择驱动视频文件'
      });
      return;
    }

    try {
      setIsCreating(true);
      await invoke('create_volcano_video_generation', { request: formData });
      addNotification({
        type: 'success',
        title: '创建成功',
        message: '视频生成任务创建成功'
      });
      setShowCreateForm(false);
      setFormData({
        name: '',
        image_url: '',
        audio_url: '',
      });
      await loadRecords();
    } catch (error) {
      console.error('创建视频生成任务失败:', error);
      addNotification({
        type: 'error',
        title: '创建失败',
        message: '创建视频生成任务失败'
      });
    } finally {
      setIsCreating(false);
    }
  }, [formData, addNotification, loadRecords]);

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

  // ============= 视频预览相关 =============

  // 打开视频预览
  const handlePreviewVideo = useCallback((record: VideoGenerationRecord) => {
    if (record.result_video_url) {
      setPreviewVideoUrl(record.result_video_url);
      setPreviewVideoTitle(record.name || '视频预览');
    } else {
      addNotification({
        type: 'warning',
        title: '预览失败',
        message: '该视频还未生成完成'
      });
    }
  }, [addNotification]);

  // 关闭视频预览
  const handleClosePreview = useCallback(() => {
    setPreviewVideoUrl(null);
    setPreviewVideoTitle('');
  }, []);

  // 下载视频
  const handleDownloadVideo = useCallback(async (videoUrl: string) => {
    try {
      const filename = `volcano_video_${Date.now()}.mp4`;
      const savedPath = await invoke('download_video_to_directory', {
        videoUrl,
        filename
      });

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

  // 批量删除选中记录
  const batchDeleteRecords = useCallback(async () => {
    if (selectedRecords.length === 0) {
      addNotification({
        type: 'warning',
        title: '选择错误',
        message: '请选择要删除的记录'
      });
      return;
    }

    try {
      await invoke('batch_delete_volcano_video_generations', { ids: selectedRecords });
      addNotification({
        type: 'success',
        title: '删除成功',
        message: `已删除 ${selectedRecords.length} 条记录`
      });
      setSelectedRecords([]);
      await loadRecords();
    } catch (error) {
      console.error('批量删除失败:', error);
      addNotification({
        type: 'error',
        title: '删除失败',
        message: '批量删除记录失败'
      });
    }
  }, [selectedRecords, addNotification, loadRecords]);

  // ============= 渲染函数 =============
  
  // 渲染状态标签
  const renderStatusBadge = (status: string) => {
    const statusConfig = {
      'Pending': { color: 'bg-yellow-100 text-yellow-800', icon: Clock, label: '等待中' },
      'Processing': { color: 'bg-blue-100 text-blue-800', icon: Loader2, label: '处理中' },
      'Completed': { color: 'bg-green-100 text-green-800', icon: CheckCircle, label: '已完成' },
      'Failed': { color: 'bg-red-100 text-red-800', icon: XCircle, label: '失败' },
    };

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig['Pending'];
    const Icon = config.icon;

    return (
      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${config.color}`}>
        <Icon className="w-3 h-3 mr-1" />
        {config.label}
      </span>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
      <div className="container mx-auto px-6 py-8">
        {/* 页面标题 */}
        <div className="mb-8">
          <div className="flex items-center space-x-3 mb-4">
            <div className="p-3 bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl shadow-lg">
              <Video className="w-8 h-8 text-white" />
            </div>
            <div>
              <h1 className="text-3xl font-bold text-gray-900">火山云视频生成</h1>
              <p className="text-gray-600 mt-1">基于火山云API的智能视频生成工具</p>
            </div>
          </div>
        </div>

        {/* 工具栏 */}
        <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
          <div className="flex items-center space-x-3">
            <button
              onClick={() => setShowCreateForm(true)}
              className="inline-flex items-center px-4 py-2 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg hover:from-blue-600 hover:to-blue-700 transition-all duration-200 shadow-md hover:shadow-lg"
            >
              <Plus className="w-4 h-4 mr-2" />
              创建任务
            </button>
            
            <button
              onClick={loadRecords}
              disabled={isLoadingRecords}
              className="inline-flex items-center px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors duration-200 disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 mr-2 ${isLoadingRecords ? 'animate-spin' : ''}`} />
              刷新
            </button>

            {selectedRecords.length > 0 && (
              <button
                onClick={batchDeleteRecords}
                className="inline-flex items-center px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors duration-200"
              >
                <Trash2 className="w-4 h-4 mr-2" />
                删除选中 ({selectedRecords.length})
              </button>
            )}
          </div>

          <div className="text-sm text-gray-500">
            共 {records.length} 条记录
          </div>
        </div>

        {/* 记录列表 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          {isLoadingRecords ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-8 h-8 animate-spin text-blue-500" />
              <span className="ml-3 text-gray-600">加载中...</span>
            </div>
          ) : records.length === 0 ? (
            <div className="text-center py-12">
              <Video className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">暂无视频生成记录</h3>
              <p className="text-gray-500 mb-6">点击"创建任务"开始生成您的第一个视频</p>
              <button
                onClick={() => setShowCreateForm(true)}
                className="inline-flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors duration-200"
              >
                <Plus className="w-4 h-4 mr-2" />
                创建任务
              </button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      <input
                        type="checkbox"
                        checked={selectedRecords.length === records.length && records.length > 0}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setSelectedRecords(records.map(r => r.id));
                          } else {
                            setSelectedRecords([]);
                          }
                        }}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      任务信息
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      状态
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      创建时间
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {records.map((record) => (
                    <tr key={record.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <input
                          type="checkbox"
                          checked={selectedRecords.includes(record.id)}
                          onChange={(e) => {
                            if (e.target.checked) {
                              setSelectedRecords([...selectedRecords, record.id]);
                            } else {
                              setSelectedRecords(selectedRecords.filter(id => id !== record.id));
                            }
                          }}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-start space-x-3">
                          <div className="flex-shrink-0">
                            {record.result_thumbnail_url ? (
                              <img
                                src={record.result_thumbnail_url}
                                alt={record.name}
                                className="w-12 h-12 rounded-lg object-cover"
                              />
                            ) : (
                              <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center">
                                <FileVideo className="w-6 h-6 text-gray-400" />
                              </div>
                            )}
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="text-sm font-medium text-gray-900 truncate">
                              {record.name}
                            </p>
                            <div className="flex items-center space-x-4 mt-1">
                              {record.image_url && (
                                <span className="inline-flex items-center text-xs text-gray-500">
                                  <ImageIcon className="w-3 h-3 mr-1" />
                                  图片
                                </span>
                              )}
                              {record.audio_url && (
                                <span className="inline-flex items-center text-xs text-gray-500">
                                  <FileVideo className="w-3 h-3 mr-1" />
                                  驱动视频
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {renderStatusBadge(record.status)}
                        {record.status === 'Processing' && (
                          <div className="mt-2">
                            <div className="w-full bg-gray-200 rounded-full h-2">
                              <div
                                className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                                style={{ width: `${record.progress}%` }}
                              ></div>
                            </div>
                            <span className="text-xs text-gray-500 mt-1">{record.progress}%</span>
                          </div>
                        )}
                        {record.error_message && (
                          <p className="text-xs text-red-500 mt-1 truncate" title={record.error_message}>
                            {record.error_message}
                          </p>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {new Date(record.created_at).toLocaleString()}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <div className="flex items-center space-x-2">
                          {record.result_video_url && (
                            <>
                              <button
                                onClick={() => handlePreviewVideo(record)}
                                className="text-blue-600 hover:text-blue-900 transition-colors duration-200"
                                title="预览视频"
                              >
                                <Eye className="w-4 h-4" />
                              </button>
                              <button
                                onClick={() => handleDownloadVideo(record.result_video_url!)}
                                className="text-green-600 hover:text-green-900 transition-colors duration-200"
                                title="下载视频"
                              >
                                <Download className="w-4 h-4" />
                              </button>
                            </>
                          )}
                          <button
                            onClick={() => deleteRecord(record.id)}
                            className="text-red-600 hover:text-red-900 transition-colors duration-200"
                            title="删除记录"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* 创建任务表单对话框 */}
        {showCreateForm && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-xl shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
              <div className="flex items-center justify-between p-6 border-b border-gray-200">
                <h2 className="text-xl font-semibold text-gray-900">创建视频生成任务</h2>
                <button
                  onClick={() => setShowCreateForm(false)}
                  className="text-gray-400 hover:text-gray-600 transition-colors duration-200"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>

              <div className="p-6 space-y-6">
                {/* 基本信息 */}
                <div className="space-y-4">
                  <h3 className="text-lg font-medium text-gray-900">基本信息</h3>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      任务名称 *
                    </label>
                    <input
                      type="text"
                      value={formData.name}
                      onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      placeholder="请输入任务名称"
                    />
                  </div>


                </div>

                {/* 文件上传 */}
                <div className="space-y-4">
                  <h3 className="text-lg font-medium text-gray-900">文件上传</h3>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      图片文件 *
                    </label>
                    <div className="flex items-center space-x-3">
                      <button
                        onClick={selectImageFile}
                        className="inline-flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors duration-200"
                      >
                        <ImageIcon className="w-4 h-4 mr-2" />
                        选择图片
                      </button>
                      {formData.image_url && (
                        <span className="text-sm text-gray-600 truncate">
                          {formData.image_url.split('/').pop() || formData.image_url}
                        </span>
                      )}
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      驱动视频文件（必需）
                    </label>
                    <div className="flex items-center space-x-3">
                      <button
                        onClick={selectAudioFile}
                        className="inline-flex items-center px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors duration-200"
                      >
                        <Video className="w-4 h-4 mr-2" />
                        选择驱动视频
                      </button>
                      {formData.audio_url && (
                        <span className="text-sm text-gray-600 truncate">
                          {formData.audio_url.split('/').pop() || formData.audio_url}
                        </span>
                      )}
                    </div>
                  </div>
                </div>

                {/* API说明 */}
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h3 className="text-lg font-medium text-blue-900 mb-2">使用说明</h3>
                  <div className="text-sm text-blue-800 space-y-1">
                    <p>• 此功能使用火山云单图视频驱动API</p>
                    <p>• 需要提供一张图片和一个驱动视频</p>
                    <p>• 系统将根据驱动视频的动作来驱动图片中的人物</p>
                    <p>• 生成的视频时长和分辨率由驱动视频决定</p>
                  </div>
                </div>
              </div>

              <div className="flex items-center justify-end space-x-3 p-6 border-t border-gray-200">
                <button
                  onClick={() => setShowCreateForm(false)}
                  className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors duration-200"
                >
                  取消
                </button>
                <button
                  onClick={createVideoGeneration}
                  disabled={isCreating}
                  className="inline-flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors duration-200 disabled:opacity-50"
                >
                  {isCreating ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      创建中...
                    </>
                  ) : (
                    <>
                      <Plus className="w-4 h-4 mr-2" />
                      创建任务
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 视频预览模态框 */}
      <VideoPreviewModal
        isOpen={!!previewVideoUrl}
        videoUrl={previewVideoUrl}
        title={previewVideoTitle}
        onClose={handleClosePreview}
        onDownload={handleDownloadVideo}
      />
    </div>
  );
};

export default VideoGenerationTool;
