import React, { useState, useEffect, useCallback } from 'react';
import {
  Image,
  FolderOpen,
  Play,
  Settings,
  Clock,
  List,
  Grid,
  RefreshCw
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';

import {
  BatchThumbnailTask,
  ThumbnailConfig,
  TimelineConfig,
  VideoFile,
  TaskStatus,
  BatchThumbnailRequest,
  FolderScanRequest,
  ThumbnailPreviewRequest,
  DEFAULT_THUMBNAIL_CONFIG,
  DEFAULT_TIMELINE_CONFIG
} from '../../types/thumbnail';

import { ThumbnailConfigPanel } from '../../components/thumbnail/ThumbnailConfigPanel';
import { TimelineConfigPanel } from '../../components/thumbnail/TimelineConfigPanel';
import { ThumbnailPreview } from '../../components/thumbnail/ThumbnailPreview';
import { BatchProgress } from '../../components/thumbnail/BatchProgress';
import { VideoFileList } from '../../components/thumbnail/VideoFileList';
import { TaskList } from '../../components/thumbnail/TaskList';

/**
 * 批量缩略图生成器主组件
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
const BatchThumbnailGenerator: React.FC = () => {
  // 状态管理
  const [selectedVideos, setSelectedVideos] = useState<VideoFile[]>([]);
  const [config, setConfig] = useState<ThumbnailConfig>(DEFAULT_THUMBNAIL_CONFIG);
  const [timelineConfig, setTimelineConfig] = useState<TimelineConfig>(DEFAULT_TIMELINE_CONFIG);
  const [enableTimeline, setEnableTimeline] = useState(false);
  const [currentTask, setCurrentTask] = useState<BatchThumbnailTask | null>(null);
  const [allTasks, setAllTasks] = useState<BatchThumbnailTask[]>([]);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [isScanning, setIsScanning] = useState(false);
  const [viewMode, setViewMode] = useState<'config' | 'progress' | 'tasks'>('config');
  const [selectedFolder, setSelectedFolder] = useState<string>('');

  // 轮询更新任务状态
  useEffect(() => {
    const interval = setInterval(() => {
      if (currentTask && currentTask.status === TaskStatus.Running) {
        updateTaskStatus(currentTask.task_id);
      }
      updateAllTasks();
    }, 2000);

    return () => clearInterval(interval);
  }, [currentTask]);

  // 选择文件夹
  const handleSelectFolder = useCallback(async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
        title: '选择视频文件夹',
      });

      if (selected && typeof selected === 'string') {
        setSelectedFolder(selected);
        await scanVideoFiles(selected);
      }
    } catch (error) {
      console.error('选择文件夹失败:', error);
    }
  }, []);

  // 扫描视频文件
  const scanVideoFiles = useCallback(async (folderPath: string) => {
    setIsScanning(true);
    try {
      const files: VideoFile[] = await invoke('scan_video_files', {
        folderPath
      });
      
      setSelectedVideos(files.filter(f => f.is_valid));
    } catch (error) {
      console.error('扫描视频文件失败:', error);
    } finally {
      setIsScanning(false);
    }
  }, []);

  // 启动批量生成
  const handleStartGeneration = useCallback(async () => {
    if (selectedVideos.length === 0) {
      alert('请先选择视频文件');
      return;
    }

    setIsGenerating(true);
    try {
      const request: BatchThumbnailRequest = {
        video_paths: selectedVideos.map(v => v.path),
        config,
        timeline_config: enableTimeline ? timelineConfig : undefined,
      };

      const taskId: string = await invoke('start_batch_thumbnail_generation', {
        request
      });

      // 获取任务详情
      const task: BatchThumbnailTask = await invoke('get_thumbnail_task_status', {
        taskId
      });

      setCurrentTask(task);
      setViewMode('progress');
    } catch (error) {
      console.error('启动批量生成失败:', error);
      alert(`启动失败: ${error}`);
    } finally {
      setIsGenerating(false);
    }
  }, [selectedVideos, config, timelineConfig, enableTimeline]);

  // 扫描文件夹并启动生成
  const handleScanAndGenerate = useCallback(async () => {
    if (!selectedFolder) {
      alert('请先选择文件夹');
      return;
    }

    setIsGenerating(true);
    try {
      const request: FolderScanRequest = {
        folder_path: selectedFolder,
        config,
        timeline_config: enableTimeline ? timelineConfig : undefined,
      };

      const taskId: string = await invoke('scan_folder_and_generate_thumbnails', {
        request
      });

      // 获取任务详情
      const task: BatchThumbnailTask = await invoke('get_thumbnail_task_status', {
        taskId
      });

      setCurrentTask(task);
      setViewMode('progress');
    } catch (error) {
      console.error('扫描并生成失败:', error);
      alert(`操作失败: ${error}`);
    } finally {
      setIsGenerating(false);
    }
  }, [selectedFolder, config, timelineConfig, enableTimeline]);

  // 更新任务状态
  const updateTaskStatus = useCallback(async (taskId: string) => {
    try {
      const task: BatchThumbnailTask = await invoke('get_thumbnail_task_status', {
        taskId
      });
      setCurrentTask(task);
    } catch (error) {
      console.error('更新任务状态失败:', error);
    }
  }, []);

  // 更新所有任务
  const updateAllTasks = useCallback(async () => {
    try {
      const tasks: BatchThumbnailTask[] = await invoke('get_all_thumbnail_tasks');
      setAllTasks(tasks);
    } catch (error) {
      console.error('获取任务列表失败:', error);
    }
  }, []);

  // 取消任务
  const handleCancelTask = useCallback(async (taskId: string) => {
    try {
      await invoke('cancel_thumbnail_task', { taskId });
      await updateTaskStatus(taskId);
    } catch (error) {
      console.error('取消任务失败:', error);
    }
  }, [updateTaskStatus]);

  // 暂停任务
  const handlePauseTask = useCallback(async (taskId: string) => {
    try {
      await invoke('pause_thumbnail_task', { taskId });
      await updateTaskStatus(taskId);
    } catch (error) {
      console.error('暂停任务失败:', error);
    }
  }, [updateTaskStatus]);

  // 恢复任务
  const handleResumeTask = useCallback(async (taskId: string) => {
    try {
      await invoke('resume_thumbnail_task', { taskId });
      await updateTaskStatus(taskId);
    } catch (error) {
      console.error('恢复任务失败:', error);
    }
  }, [updateTaskStatus]);

  // 预览缩略图
  const handlePreviewThumbnail = useCallback(async (videoPath: string, timestamp: number) => {
    try {
      const request: ThumbnailPreviewRequest = {
        video_path: videoPath,
        timestamp,
        width: config.size.width,
        height: config.size.height,
      };

      const dataUrl: string = await invoke('preview_thumbnail', { request });
      setPreviewImage(dataUrl);
    } catch (error) {
      console.error('预览缩略图失败:', error);
    }
  }, [config.size]);

  // 清理已完成任务
  const handleCleanupTasks = useCallback(async () => {
    try {
      const removedCount: number = await invoke('cleanup_completed_thumbnail_tasks');
      alert(`已清理 ${removedCount} 个已完成的任务`);
      await updateAllTasks();
    } catch (error) {
      console.error('清理任务失败:', error);
    }
  }, [updateAllTasks]);

  // 初始化时获取任务列表
  useEffect(() => {
    updateAllTasks();
  }, [updateAllTasks]);

  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-blue-500 to-blue-600 rounded-xl flex items-center justify-center shadow-lg hover:shadow-xl transition-all duration-300">
            <Image className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-900 to-blue-600 bg-clip-text text-transparent">
              批量缩略图生成器
            </h1>
            <p className="text-gray-600 text-lg">为视频文件批量生成预览缩略图和时间轴</p>
          </div>
        </div>

        {/* 视图切换 */}
        <div className="flex items-center gap-2">
          <button
            onClick={() => setViewMode('config')}
            className={`px-4 py-2 rounded-lg transition-colors ${
              viewMode === 'config'
                ? 'bg-primary-100 text-primary-600'
                : 'text-gray-400 hover:text-gray-600'
            }`}
          >
            <Settings className="w-5 h-5" />
          </button>
          <button
            onClick={() => setViewMode('progress')}
            className={`px-4 py-2 rounded-lg transition-colors ${
              viewMode === 'progress'
                ? 'bg-primary-100 text-primary-600'
                : 'text-gray-400 hover:text-gray-600'
            }`}
          >
            <Clock className="w-5 h-5" />
          </button>
          <button
            onClick={() => setViewMode('tasks')}
            className={`px-4 py-2 rounded-lg transition-colors ${
              viewMode === 'tasks'
                ? 'bg-primary-100 text-primary-600'
                : 'text-gray-400 hover:text-gray-600'
            }`}
          >
            <List className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* 主要内容区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧：文件选择和配置 */}
        <div className="lg:col-span-2 space-y-6">
          {viewMode === 'config' && (
            <>
              {/* 文件选择区域 */}
              <div className="card p-6">
                <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                  <FolderOpen className="w-5 h-5" />
                  视频文件选择
                </h3>
                
                <div className="space-y-4">
                  <div className="flex gap-4">
                    <button
                      onClick={handleSelectFolder}
                      disabled={isScanning}
                      className="btn btn-primary"
                    >
                      <FolderOpen className="w-4 h-4 flex-shrink-0" />
                      {isScanning ? '扫描中...' : '选择文件夹'}
                    </button>
                    
                    {selectedFolder && (
                      <div className="flex-1 px-3 py-2 bg-gray-50 rounded-lg text-sm text-gray-600">
                        {selectedFolder}
                      </div>
                    )}
                  </div>

                  {selectedVideos.length > 0 && (
                    <VideoFileList
                      videos={selectedVideos}
                      onPreview={handlePreviewThumbnail}
                    />
                  )}
                </div>
              </div>

              {/* 配置面板 */}
              <ThumbnailConfigPanel
                config={config}
                onChange={setConfig}
              />

              {/* 时间轴配置 */}
              <div className="card p-6">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold flex items-center gap-2">
                    <Grid className="w-5 h-5" />
                    时间轴缩略图
                  </h3>
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={enableTimeline}
                      onChange={(e) => setEnableTimeline(e.target.checked)}
                      className="rounded"
                    />
                    <span className="text-sm">启用时间轴生成</span>
                  </label>
                </div>

                {enableTimeline && (
                  <TimelineConfigPanel
                    config={timelineConfig}
                    onChange={setTimelineConfig}
                  />
                )}
              </div>

              {/* 操作按钮 */}
              <div className="flex gap-4">
                <button
                  onClick={handleStartGeneration}
                  disabled={isGenerating || selectedVideos.length === 0}
                  className="btn btn-primary"
                >
                  <Play className="w-4 h-4" />
                  {isGenerating ? '生成中...' : '开始生成'}
                </button>

                <button
                  onClick={handleScanAndGenerate}
                  disabled={isGenerating || !selectedFolder}
                  className="btn btn-secondary"
                >
                  <RefreshCw className="w-4 h-4" />
                  扫描并生成
                </button>
              </div>
            </>
          )}

          {viewMode === 'progress' && currentTask && (
            <BatchProgress
              task={currentTask}
              onCancel={() => handleCancelTask(currentTask.task_id)}
              onPause={() => handlePauseTask(currentTask.task_id)}
              onResume={() => handleResumeTask(currentTask.task_id)}
            />
          )}

          {viewMode === 'tasks' && (
            <TaskList
              tasks={allTasks}
              onCancel={handleCancelTask}
              onPause={handlePauseTask}
              onResume={handleResumeTask}
              onCleanup={handleCleanupTasks}
            />
          )}
        </div>

        {/* 右侧：预览区域 */}
        <div className="space-y-6">
          {previewImage && (
            <ThumbnailPreview
              imageUrl={previewImage}
              onClose={() => setPreviewImage(null)}
            />
          )}

          {/* 统计信息 */}
          <div className="card p-6">
            <h3 className="text-lg font-semibold mb-4">统计信息</h3>
            <div className="space-y-3">
              <div className="flex justify-between">
                <span className="text-gray-600">选中视频:</span>
                <span className="font-medium">{selectedVideos.length} 个</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">活跃任务:</span>
                <span className="font-medium">
                  {allTasks.filter(t => t.status === TaskStatus.Running).length} 个
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">已完成任务:</span>
                <span className="font-medium">
                  {allTasks.filter(t => t.status === TaskStatus.Completed).length} 个
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default BatchThumbnailGenerator;
