import React, { useState, useEffect } from 'react';
import {
  ArrowLeft,
  Video,
  Settings,
  Play,
  Copy,
  Sparkles,
  FolderOpen,
  FileVideo,
  Wand2,
  Gauge,
  Maximize,
  RotateCcw,
  Eye,
  Sun,
  ChevronDown,
  ChevronRight,
  RefreshCw
} from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { fetchTopazTemplates, TemplateInfo } from '../services/topazTemplateService';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';

// 完整的 Topaz 设置接口
interface TopazSettings {
  stabilize: {
    active: boolean;
    smooth: number;
    method: number;
    rsc: boolean;
    reduce_motion: boolean;
    reduce_motion_iteration: number;
  };
  motionblur: {
    active: boolean;
    model: string;
    model_name?: string;
  };
  slowmo: {
    active: boolean;
    model: string;
    factor: number;
    duplicate: boolean;
    duplicate_threshold: number;
  };
  enhance: {
    active: boolean;
    model: string;
    video_type: number;
    auto: number;
    field_order: number;
    compress: number;
    detail: number;
    sharpen: number;
    denoise: number;
    dehalo: number;
    deblur: number;
    add_noise: number;
    recover_original_detail_value: number;
    focus_fix_level?: string;
    is_artemis: boolean;
    is_gaia: boolean;
    is_theia: boolean;
    is_proteus: boolean;
    is_iris: boolean;
    is_second_enhancement?: boolean;
  };
  grain: {
    active: boolean;
    grain: number;
    grain_size: number;
  };
  output: {
    active: boolean;
    out_size_method: number;
    crop_to_fit: boolean;
    output_par: number;
    out_fps: number;
    lock_aspect_ratio?: boolean;
    custom_resolution_priority?: number;
  };
  hdr?: {
    active: boolean;
    model: string;
    auto: number;
    exposure: number;
    field_order: number;
    hdr_output_trc: number;
    saturation: number;
    sdr_inflection_point: number;
    video_type: number;
  };
  second_enhance?: {
    active: boolean;
    model: string;
    video_type: number;
    auto: number;
    field_order: number;
    compress: number;
    detail: number;
    sharpen: number;
    denoise: number;
    dehalo: number;
    deblur: number;
    add_noise: number;
    recover_original_detail_value: number;
    focus_fix_level?: string;
  };
  filter_manager?: {
    second_enhancement_enabled: boolean;
    second_enhancement_intermediate_resolution: number;
  };
}

const TopazVideoAIConfigurator: React.FC = () => {
  const navigate = useNavigate();
  
  // 基础状态
  const [currentTemplate, setCurrentTemplate] = useState<string | null>(null);
  const [templates, setTemplates] = useState<Record<string, TemplateInfo>>({});
  const [templatesLoading, setTemplatesLoading] = useState(true);
  
  // 文件设置
  const [inputFile, setInputFile] = useState('');
  const [outputFolder, setOutputFolder] = useState('');
  const [outputFilename, setOutputFilename] = useState('enhanced_video.mp4');
  
  // 处理设置
  const [processingMode, setProcessingMode] = useState('single');
  const [rateControl, setRateControl] = useState('constqp');
  
  // UI 状态
  const [activeSection, setActiveSection] = useState<string>('files');
  const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['files']));
  const [generatedCommand, setGeneratedCommand] = useState('');
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  // 视频处理状态
  const [isProcessing, setIsProcessing] = useState(false);
  const [processingProgress, setProcessingProgress] = useState(0);
  const [processingStatus, setProcessingStatus] = useState('');
  const [processingError, setProcessingError] = useState('');

  // 默认设置
  const [settings, setSettings] = useState<TopazSettings>({
    stabilize: {
      active: false,
      smooth: 50,
      method: 1,
      rsc: false,
      reduce_motion: false,
      reduce_motion_iteration: 2
    },
    motionblur: {
      active: false,
      model: "thm-2",
      model_name: "thm-2"
    },
    slowmo: {
      active: false,
      model: "apo-8",
      factor: 2,
      duplicate: true,
      duplicate_threshold: 10
    },
    enhance: {
      active: true,
      model: "alq-13",
      video_type: 1,
      auto: 0,
      field_order: 0,
      compress: 0,
      detail: 0,
      sharpen: 0,
      denoise: 0,
      dehalo: 0,
      deblur: 0,
      add_noise: 0,
      recover_original_detail_value: 20,
      is_artemis: false,
      is_gaia: false,
      is_theia: false,
      is_proteus: false,
      is_iris: false
    },
    grain: {
      active: false,
      grain: 5,
      grain_size: 2
    },
    output: {
      active: true,
      out_size_method: 0,
      crop_to_fit: false,
      output_par: 0,
      out_fps: 0,
      lock_aspect_ratio: true
    },
    hdr: {
      active: false,
      model: "hyp-1",
      auto: 0,
      exposure: 0,
      field_order: 0,
      hdr_output_trc: 0,
      saturation: 0,
      sdr_inflection_point: 0.7,
      video_type: 1
    }
  });

  // 加载模板数据
  useEffect(() => {
    const loadTemplates = async () => {
      setTemplatesLoading(true);
      try {
        const templateData = await fetchTopazTemplates();
        setTemplates(templateData);
      } catch (error) {
        console.error('加载模板失败:', error);
        setTemplates({});
      } finally {
        setTemplatesLoading(false);
      }
    };

    loadTemplates();
  }, []);

  // 选择模板
  const selectTemplate = (templateKey: string) => {
    setCurrentTemplate(templateKey);
    const template = templates[templateKey];
    if (template) {
      setSettings(template.settings as TopazSettings);
    }
  };

  // 更新设置
  const updateSetting = (category: keyof TopazSettings, field: string, value: any) => {
    setSettings(prev => ({
      ...prev,
      [category]: {
        ...prev[category],
        [field]: value
      }
    }));
  };

  // 切换展开状态
  const toggleSection = (section: string) => {
    const newExpanded = new Set(expandedSections);
    if (newExpanded.has(section)) {
      newExpanded.delete(section);
    } else {
      newExpanded.add(section);
    }
    setExpandedSections(newExpanded);
  };

  // 文件选择
  const selectInputFile = async () => {
    try {
      const filters = [
        ['视频文件', ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'webm', 'm4v', 'mpg', 'mpeg', '3gp']],
        ['所有文件', ['*']]
      ];
      const filePath = await invoke<string | null>('select_file_with_options', {
        filters,
        title: '选择输入视频文件',
        defaultDirectory: null
      });
      if (filePath) {
        setInputFile(filePath);
      }
    } catch (error) {
      console.error('选择文件失败:', error);
    }
  };

  const selectOutputFolder = async () => {
    try {
      const folderPath = await invoke<string | null>('select_directory_with_options', {
        title: '选择输出文件夹',
        defaultDirectory: outputFolder || null
      });
      if (folderPath) {
        setOutputFolder(folderPath);
      }
    } catch (error) {
      console.error('选择文件夹失败:', error);
    }
  };

  // 获取文件名（用于显示）
  const getFileName = (filePath: string) => {
    if (!filePath) return '';
    return filePath.split(/[/\\]/).pop() || filePath;
  };

  // 生成命令
  const generateCommand = async () => {
    if (!inputFile || !outputFolder) {
      setToastMessage('请选择输入文件和输出文件夹！');
      setShowToast(true);
      setTimeout(() => setShowToast(false), 3000);
      return;
    }

    try {
      // 构建完整的输出路径
      const fullOutputPath = `${outputFolder}/${outputFilename}`;

      // 转换设置格式
      const backendSettings = convertSettingsToBackendFormat(settings);

      // 调用后端生成命令
      const result = await invoke('generate_topaz_command', {
        settings: backendSettings,
        inputFile,
        outputFile: fullOutputPath,
        processingMode,
        rateControl,
      });

      setGeneratedCommand(result as string);
      setToastMessage('命令生成成功！');
      setShowToast(true);
      setTimeout(() => setShowToast(false), 3000);

    } catch (error) {
      console.error('生成命令失败:', error);
      setToastMessage('命令生成失败！');
      setShowToast(true);
      setTimeout(() => setShowToast(false), 3000);
    }
  };

  // 复制命令
  const copyCommand = async () => {
    try {
      await navigator.clipboard.writeText(generatedCommand);
      setToastMessage('命令已复制到剪贴板！');
      setShowToast(true);
      setTimeout(() => setShowToast(false), 3000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  // 转换设置格式为后端期望的格式
  const convertSettingsToBackendFormat = (frontendSettings: TopazSettings) => {
    return {
      stabilize: {
        active: frontendSettings.stabilize.active || false,
        smooth: frontendSettings.stabilize.smooth || 50,
        method: frontendSettings.stabilize.method || 1,
        rsc: frontendSettings.stabilize.rsc || false,
        reduce_motion: frontendSettings.stabilize.reduce_motion ? 1 : 0,
        reduce_motion_iteration: frontendSettings.stabilize.reduce_motion_iteration || 2,
      },
      motionblur: {
        active: frontendSettings.motionblur.active || false,
        model: frontendSettings.motionblur.model || "thm-2",
        model_name: frontendSettings.motionblur.model_name || frontendSettings.motionblur.model || "thm-2",
      },
      slowmo: {
        active: frontendSettings.slowmo.active || false,
        model: frontendSettings.slowmo.model || "apo-8",
        factor: frontendSettings.slowmo.factor || 2,
        duplicate: frontendSettings.slowmo.duplicate || true,
        duplicate_threshold: frontendSettings.slowmo.duplicate_threshold || 10,
      },
      enhance: {
        active: frontendSettings.enhance.active,
        model: frontendSettings.enhance.model,
        video_type: frontendSettings.enhance.video_type || 1,
        compress: frontendSettings.enhance.compress || 0,
        detail: frontendSettings.enhance.detail || 0,
        sharpen: frontendSettings.enhance.sharpen || 0,
        denoise: frontendSettings.enhance.denoise || 0,
        dehalo: frontendSettings.enhance.dehalo || 0,
        deblur: frontendSettings.enhance.deblur || 0,
        auto: frontendSettings.enhance.auto || 0,
        recover_original_detail_value: frontendSettings.enhance.recover_original_detail_value || 20,
      },
      grain: {
        active: frontendSettings.grain.active || false,
        grain: frontendSettings.grain.grain || 5,
        grain_size: frontendSettings.grain.grain_size || 2,
      },
      output: {
        active: frontendSettings.output.active || true,
        out_size_method: frontendSettings.output.out_size_method || 0,
        out_fps: frontendSettings.output.out_fps || 0,
        crop_to_fit: frontendSettings.output.crop_to_fit || false,
        lock_aspect_ratio: frontendSettings.output.lock_aspect_ratio || false,
      },
      hdr: {
        active: frontendSettings.hdr?.active || false,
        model: frontendSettings.hdr?.model || "hyp-1",
        auto: frontendSettings.hdr?.auto || 0,
        exposure: frontendSettings.hdr?.exposure || 0,
        saturation: frontendSettings.hdr?.saturation || 0,
        sdr_inflection_point: frontendSettings.hdr?.sdr_inflection_point || 0.7,
      },
    };
  };

  // 开始处理视频
  const startVideoProcessing = async () => {
    if (!inputFile || !outputFolder) {
      setToastMessage('请选择输入文件和输出文件夹！');
      setShowToast(true);
      setTimeout(() => setShowToast(false), 3000);
      return;
    }

    try {
      setIsProcessing(true);
      setProcessingProgress(0);
      setProcessingStatus('正在准备处理...');
      setProcessingError('');

      // 构建完整的输出路径
      const fullOutputPath = `${outputFolder}/${outputFilename}`;

      // 转换设置格式
      const backendSettings = convertSettingsToBackendFormat(settings);

      // 监听进度事件
      const unlisten = await listen('topaz-progress', (event: any) => {
        const { progress, status, error } = event.payload;
        setProcessingProgress(progress);
        setProcessingStatus(status);
        if (error) {
          setProcessingError(error);
        }
      });

      try {
        // 调用带进度监控的 Tauri 命令
        await invoke('execute_topaz_video_processing_with_progress', {
          settings: backendSettings,
          inputFile,
          outputFile: fullOutputPath,
          processingMode,
          rateControl,
        });

        setToastMessage('视频处理完成！');
        setShowToast(true);
        setTimeout(() => setShowToast(false), 3000);

      } finally {
        // 清理事件监听器
        unlisten();
      }

    } catch (error) {
      console.error('视频处理失败:', error);
      setProcessingError(String(error));
      setProcessingStatus('处理失败');
      setToastMessage('视频处理失败！');
      setShowToast(true);
      setTimeout(() => setShowToast(false), 3000);
    } finally {
      setIsProcessing(false);
      // 不重置进度，让用户看到最终状态
    }
  };

  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="flex items-center justify-between h-16">
            <div className="flex items-center">
              <button
                onClick={() => navigate('/tools')}
                className="flex items-center text-gray-600 hover:text-gray-900 transition-colors"
              >
                <ArrowLeft className="w-5 h-5 mr-2" />
                返回工具列表
              </button>
            </div>
            <div className="flex items-center space-x-4">
              <div className="flex items-center space-x-2">
                <Video className="w-6 h-6 text-blue-600" />
                <h1 className="text-xl font-semibold text-gray-900">Topaz Video AI 参数配置器</h1>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 左侧：模板和文件设置 */}
          <div className="space-y-6">
            {/* 模板选择 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                  <Sparkles className="w-5 h-5 text-blue-500 mr-2" />
                  内置模板 ({templatesLoading ? '加载中...' : Object.keys(templates).length})
                </h3>

                {templatesLoading ? (
                  <div className="flex items-center justify-center py-8">
                    <RefreshCw className="w-6 h-6 animate-spin text-blue-500" />
                    <span className="ml-2 text-gray-600">加载模板中...</span>
                  </div>
                ) : (
                  <div className="space-y-2 max-h-96 overflow-y-auto">
                    {Object.entries(templates).map(([key, template]) => (
                      <div
                        key={key}
                        className={`p-3 rounded-lg border-2 cursor-pointer transition-all duration-200 ${
                          currentTemplate === key
                            ? 'border-blue-500 bg-blue-50'
                            : 'border-gray-200 hover:border-blue-300 hover:bg-gray-50'
                        }`}
                        onClick={() => selectTemplate(key)}
                      >
                        <div className="flex items-start space-x-3">
                          <span className="text-lg">{template.icon || '📄'}</span>
                          <div className="flex-1 min-w-0">
                            <h4 className="text-sm font-medium text-gray-900 truncate">{template.name}</h4>
                            <p className="text-xs text-gray-600 mt-1 line-clamp-2">{template.description}</p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>

            {/* 文件设置 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                  <FileVideo className="w-5 h-5 text-green-500 mr-2" />
                  文件设置
                </h3>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">输入文件</label>
                    <div className="flex space-x-2">
                      <div className="flex-1">
                        <input
                          type="text"
                          value={inputFile}
                          onChange={(e) => setInputFile(e.target.value)}
                          placeholder="选择输入视频文件..."
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                          title={inputFile} // 显示完整路径的提示
                        />
                        {inputFile && (
                          <div className="text-xs text-gray-500 mt-1 truncate" title={inputFile}>
                            {getFileName(inputFile)}
                          </div>
                        )}
                      </div>
                      <button
                        onClick={selectInputFile}
                        className="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors"
                      >
                        <FolderOpen className="w-4 h-4" />
                      </button>
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">输出文件夹</label>
                    <div className="flex space-x-2">
                      <div className="flex-1">
                        <input
                          type="text"
                          value={outputFolder}
                          onChange={(e) => setOutputFolder(e.target.value)}
                          placeholder="选择输出文件夹..."
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                          title={outputFolder} // 显示完整路径的提示
                        />
                        {outputFolder && (
                          <div className="text-xs text-gray-500 mt-1 truncate" title={outputFolder}>
                            📁 {outputFolder}
                          </div>
                        )}
                      </div>
                      <button
                        onClick={selectOutputFolder}
                        className="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors"
                      >
                        <FolderOpen className="w-4 h-4" />
                      </button>
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">输出文件名</label>
                    <input
                      type="text"
                      value={outputFilename}
                      onChange={(e) => setOutputFilename(e.target.value)}
                      placeholder="enhanced_video.mp4"
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* 中间：参数配置 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 处理模式设置 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                  <Settings className="w-5 h-5 text-purple-500 mr-2" />
                  处理模式
                </h3>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">处理模式</label>
                    <select
                      value={processingMode}
                      onChange={(e) => setProcessingMode(e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    >
                      <option value="single">单阶段处理</option>
                      <option value="two_pass">两阶段处理 (真实 Topaz)</option>
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">率控制模式</label>
                    <select
                      value={rateControl}
                      onChange={(e) => setRateControl(e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    >
                      <option value="constqp">恒定 QP (推荐)</option>
                      <option value="cbr">恒定比特率</option>
                      <option value="vbr">可变比特率</option>
                      <option value="crf">CRF</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>

            {/* 防抖设置 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <div
                  className="flex items-center justify-between cursor-pointer"
                  onClick={() => toggleSection('stabilize')}
                >
                  <h3 className="text-lg font-medium text-gray-900 flex items-center">
                    <RotateCcw className="w-5 h-5 text-orange-500 mr-2" />
                    防抖设置
                  </h3>
                  <div className="flex items-center space-x-2">
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={settings.stabilize.active}
                        onChange={(e) => updateSetting('stabilize', 'active', e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-600">启用</span>
                    </label>
                    {expandedSections.has('stabilize') ?
                      <ChevronDown className="w-5 h-5 text-gray-400" /> :
                      <ChevronRight className="w-5 h-5 text-gray-400" />
                    }
                  </div>
                </div>

                {expandedSections.has('stabilize') && settings.stabilize.active && (
                  <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">平滑级别 (0-100)</label>
                      <input
                        type="number"
                        min="0"
                        max="100"
                        value={settings.stabilize.smooth}
                        onChange={(e) => updateSetting('stabilize', 'smooth', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">防抖方法</label>
                      <select
                        value={settings.stabilize.method}
                        onChange={(e) => updateSetting('stabilize', 'method', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value={0}>自动裁剪</option>
                        <option value={1}>无裁剪</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">减少运动迭代次数</label>
                      <input
                        type="number"
                        min="1"
                        max="5"
                        value={settings.stabilize.reduce_motion_iteration}
                        onChange={(e) => updateSetting('stabilize', 'reduce_motion_iteration', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      />
                    </div>

                    <div className="flex items-center">
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          checked={settings.stabilize.rsc}
                          onChange={(e) => updateSetting('stabilize', 'rsc', e.target.checked)}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <span className="ml-2 text-sm text-gray-700">滚动快门校正</span>
                      </label>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* 运动模糊去除设置 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <div
                  className="flex items-center justify-between cursor-pointer"
                  onClick={() => toggleSection('motionblur')}
                >
                  <h3 className="text-lg font-medium text-gray-900 flex items-center">
                    <Eye className="w-5 h-5 text-red-500 mr-2" />
                    运动模糊去除
                  </h3>
                  <div className="flex items-center space-x-2">
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={settings.motionblur.active}
                        onChange={(e) => updateSetting('motionblur', 'active', e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-600">启用</span>
                    </label>
                    {expandedSections.has('motionblur') ?
                      <ChevronDown className="w-5 h-5 text-gray-400" /> :
                      <ChevronRight className="w-5 h-5 text-gray-400" />
                    }
                  </div>
                </div>

                {expandedSections.has('motionblur') && settings.motionblur.active && (
                  <div className="mt-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">模型</label>
                      <select
                        value={settings.motionblur.model}
                        onChange={(e) => updateSetting('motionblur', 'model', e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="thm-2">thm-2 (推荐)</option>
                        <option value="thm-1">thm-1</option>
                      </select>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* 慢动作设置 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <div
                  className="flex items-center justify-between cursor-pointer"
                  onClick={() => toggleSection('slowmo')}
                >
                  <h3 className="text-lg font-medium text-gray-900 flex items-center">
                    <Gauge className="w-5 h-5 text-yellow-500 mr-2" />
                    慢动作/插帧
                  </h3>
                  <div className="flex items-center space-x-2">
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={settings.slowmo.active}
                        onChange={(e) => updateSetting('slowmo', 'active', e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-600">启用</span>
                    </label>
                    {expandedSections.has('slowmo') ?
                      <ChevronDown className="w-5 h-5 text-gray-400" /> :
                      <ChevronRight className="w-5 h-5 text-gray-400" />
                    }
                  </div>
                </div>

                {expandedSections.has('slowmo') && settings.slowmo.active && (
                  <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">插帧模型</label>
                      <select
                        value={settings.slowmo.model}
                        onChange={(e) => updateSetting('slowmo', 'model', e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="apo-8">apo-8 (推荐)</option>
                        <option value="apo-4">apo-4</option>
                        <option value="chro-3">chro-3</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">慢动作倍数</label>
                      <select
                        value={settings.slowmo.factor}
                        onChange={(e) => updateSetting('slowmo', 'factor', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value={2}>2x</option>
                        <option value={4}>4x</option>
                        <option value={8}>8x</option>
                        <option value={16}>16x</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">重复阈值 (0-100)</label>
                      <input
                        type="number"
                        min="0"
                        max="100"
                        value={settings.slowmo.duplicate_threshold}
                        onChange={(e) => updateSetting('slowmo', 'duplicate_threshold', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      />
                    </div>

                    <div className="flex items-center">
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          checked={settings.slowmo.duplicate}
                          onChange={(e) => updateSetting('slowmo', 'duplicate', e.target.checked)}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <span className="ml-2 text-sm text-gray-700">允许重复帧</span>
                      </label>
                    </div>
                  </div>
                )}
              </div>
            </div>
            {/* AI 增强设置 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <div
                  className="flex items-center justify-between cursor-pointer"
                  onClick={() => toggleSection('enhance')}
                >
                  <h3 className="text-lg font-medium text-gray-900 flex items-center">
                    <Wand2 className="w-5 h-5 text-purple-500 mr-2" />
                    AI 增强设置
                  </h3>
                  <div className="flex items-center space-x-2">
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={settings.enhance.active}
                        onChange={(e) => updateSetting('enhance', 'active', e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-600">启用</span>
                    </label>
                    {expandedSections.has('enhance') ?
                      <ChevronDown className="w-5 h-5 text-gray-400" /> :
                      <ChevronRight className="w-5 h-5 text-gray-400" />
                    }
                  </div>
                </div>

                {expandedSections.has('enhance') && settings.enhance.active && (
                  <div className="mt-4 space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">AI 增强模型</label>
                        <select
                          value={settings.enhance.model}
                          onChange={(e) => updateSetting('enhance', 'model', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        >
                          <option value="alq-13">alq-13 (通用)</option>
                          <option value="prob-4">prob-4 (高质量)</option>
                          <option value="ghq-5">ghq-5 (游戏)</option>
                          <option value="rhea-1">rhea-1 (胶片)</option>
                        </select>
                      </div>

                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">视频类型</label>
                        <select
                          value={settings.enhance.video_type}
                          onChange={(e) => updateSetting('enhance', 'video_type', parseInt(e.target.value))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        >
                          <option value={0}>隔行扫描</option>
                          <option value={1}>逐行扫描</option>
                        </select>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">细节 (0-100)</label>
                        <input
                          type="number"
                          min="0"
                          max="100"
                          value={settings.enhance.detail}
                          onChange={(e) => updateSetting('enhance', 'detail', parseInt(e.target.value))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        />
                      </div>

                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">锐化 (0-100)</label>
                        <input
                          type="number"
                          min="0"
                          max="100"
                          value={settings.enhance.sharpen}
                          onChange={(e) => updateSetting('enhance', 'sharpen', parseInt(e.target.value))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        />
                      </div>

                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">降噪 (0-100)</label>
                        <input
                          type="number"
                          min="0"
                          max="100"
                          value={settings.enhance.denoise}
                          onChange={(e) => updateSetting('enhance', 'denoise', parseInt(e.target.value))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        />
                      </div>

                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">去模糊 (0-100)</label>
                        <input
                          type="number"
                          min="0"
                          max="100"
                          value={settings.enhance.deblur}
                          onChange={(e) => updateSetting('enhance', 'deblur', parseInt(e.target.value))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        />
                      </div>
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">去光晕 (0-100)</label>
                        <input
                          type="number"
                          min="0"
                          max="100"
                          value={settings.enhance.dehalo}
                          onChange={(e) => updateSetting('enhance', 'dehalo', parseInt(e.target.value))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        />
                      </div>

                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">压缩修复 (0-100)</label>
                        <input
                          type="number"
                          min="0"
                          max="100"
                          value={settings.enhance.compress}
                          onChange={(e) => updateSetting('enhance', 'compress', parseInt(e.target.value))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        />
                      </div>

                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">原始细节恢复 (0-100)</label>
                        <input
                          type="number"
                          min="0"
                          max="100"
                          value={settings.enhance.recover_original_detail_value}
                          onChange={(e) => updateSetting('enhance', 'recover_original_detail_value', parseInt(e.target.value))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        />
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* 输出设置 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <div
                  className="flex items-center justify-between cursor-pointer"
                  onClick={() => toggleSection('output')}
                >
                  <h3 className="text-lg font-medium text-gray-900 flex items-center">
                    <Maximize className="w-5 h-5 text-green-500 mr-2" />
                    输出设置
                  </h3>
                  <div className="flex items-center space-x-2">
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={settings.output.active}
                        onChange={(e) => updateSetting('output', 'active', e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-600">启用</span>
                    </label>
                    {expandedSections.has('output') ?
                      <ChevronDown className="w-5 h-5 text-gray-400" /> :
                      <ChevronRight className="w-5 h-5 text-gray-400" />
                    }
                  </div>
                </div>

                {expandedSections.has('output') && settings.output.active && (
                  <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">输出尺寸</label>
                      <select
                        value={settings.output.out_size_method}
                        onChange={(e) => updateSetting('output', 'out_size_method', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value={0}>原始尺寸</option>
                        <option value={1}>2x 放大</option>
                        <option value={2}>3x 放大</option>
                        <option value={3}>4x 放大</option>
                        <option value={7}>自定义</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">输出帧率 (0=保持原始)</label>
                      <input
                        type="number"
                        min="0"
                        max="120"
                        value={settings.output.out_fps}
                        onChange={(e) => updateSetting('output', 'out_fps', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      />
                    </div>

                    <div className="flex items-center">
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          checked={settings.output.lock_aspect_ratio}
                          onChange={(e) => updateSetting('output', 'lock_aspect_ratio', e.target.checked)}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <span className="ml-2 text-sm text-gray-700">锁定宽高比</span>
                      </label>
                    </div>

                    <div className="flex items-center">
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          checked={settings.output.crop_to_fit}
                          onChange={(e) => updateSetting('output', 'crop_to_fit', e.target.checked)}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <span className="ml-2 text-sm text-gray-700">裁剪适应</span>
                      </label>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* HDR 设置 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <div
                  className="flex items-center justify-between cursor-pointer"
                  onClick={() => toggleSection('hdr')}
                >
                  <h3 className="text-lg font-medium text-gray-900 flex items-center">
                    <Sun className="w-5 h-5 text-yellow-500 mr-2" />
                    HDR 处理
                  </h3>
                  <div className="flex items-center space-x-2">
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={settings.hdr?.active || false}
                        onChange={(e) => updateSetting('hdr', 'active', e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-600">启用</span>
                    </label>
                    {expandedSections.has('hdr') ?
                      <ChevronDown className="w-5 h-5 text-gray-400" /> :
                      <ChevronRight className="w-5 h-5 text-gray-400" />
                    }
                  </div>
                </div>

                {expandedSections.has('hdr') && settings.hdr?.active && (
                  <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">HDR 模型</label>
                      <select
                        value={settings.hdr?.model || 'hyp-1'}
                        onChange={(e) => updateSetting('hdr', 'model', e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="hyp-1">Hyperion v1</option>
                        <option value="hyp-2">Hyperion v2</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">视频类型</label>
                      <select
                        value={settings.hdr?.video_type || 1}
                        onChange={(e) => updateSetting('hdr', 'video_type', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value={0}>隔行扫描</option>
                        <option value={1}>逐行扫描</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">自动级别 (0-100)</label>
                      <input
                        type="range"
                        min="0"
                        max="100"
                        value={settings.hdr?.auto || 0}
                        onChange={(e) => updateSetting('hdr', 'auto', parseInt(e.target.value))}
                        className="w-full"
                      />
                      <div className="text-sm text-gray-500 mt-1">{settings.hdr?.auto || 0}</div>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">曝光调整 (0-100)</label>
                      <input
                        type="range"
                        min="0"
                        max="100"
                        value={settings.hdr?.exposure || 0}
                        onChange={(e) => updateSetting('hdr', 'exposure', parseInt(e.target.value))}
                        className="w-full"
                      />
                      <div className="text-sm text-gray-500 mt-1">{settings.hdr?.exposure || 0}</div>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">饱和度调整 (0-100)</label>
                      <input
                        type="range"
                        min="0"
                        max="100"
                        value={settings.hdr?.saturation || 0}
                        onChange={(e) => updateSetting('hdr', 'saturation', parseInt(e.target.value))}
                        className="w-full"
                      />
                      <div className="text-sm text-gray-500 mt-1">{settings.hdr?.saturation || 0}</div>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">SDR 拐点 (0.0-1.0)</label>
                      <input
                        type="range"
                        min="0"
                        max="100"
                        value={(settings.hdr?.sdr_inflection_point || 0.7) * 100}
                        onChange={(e) => updateSetting('hdr', 'sdr_inflection_point', parseInt(e.target.value) / 100)}
                        className="w-full"
                      />
                      <div className="text-sm text-gray-500 mt-1">{(settings.hdr?.sdr_inflection_point || 0.7).toFixed(2)}</div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* 视频处理 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              <div className="p-6">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                  <Play className="w-5 h-5 text-blue-500 mr-2" />
                  视频处理
                </h3>

                <div className="space-y-4">
                  {!isProcessing ? (
                    <div className="space-y-3">
                      <button
                        onClick={startVideoProcessing}
                        disabled={!inputFile || !outputFolder}
                        className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors font-medium flex items-center justify-center"
                      >
                        <Play className="w-5 h-5 mr-2" />
                        立即开始处理视频
                      </button>

                      <div className="flex space-x-2">
                        <button
                          onClick={generateCommand}
                          className="flex-1 bg-gray-100 text-gray-700 py-2 px-4 rounded-lg hover:bg-gray-200 transition-colors flex items-center justify-center"
                        >
                          <Settings className="w-4 h-4 mr-2" />
                          预览命令
                        </button>
                        {generatedCommand && (
                          <button
                            onClick={copyCommand}
                            className="flex-1 bg-gray-100 text-gray-700 py-2 px-4 rounded-lg hover:bg-gray-200 transition-colors flex items-center justify-center"
                          >
                            <Copy className="w-4 h-4 mr-2" />
                            复制命令
                          </button>
                        )}
                      </div>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      <div className="text-center">
                        <div className="inline-flex items-center px-4 py-2 bg-blue-100 text-blue-800 rounded-lg">
                          <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
                          {processingStatus}
                        </div>
                      </div>

                      <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: `${processingProgress}%` }}
                        ></div>
                      </div>

                      <div className="text-center text-sm text-gray-600">
                        {processingProgress}% 完成
                      </div>
                    </div>
                  )}

                  {processingError && (
                    <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                      <div className="flex items-center">
                        <div className="text-red-600 font-medium">处理失败</div>
                      </div>
                      <div className="text-red-700 text-sm mt-1">{processingError}</div>
                    </div>
                  )}

                  {generatedCommand && !isProcessing && (
                    <div className="space-y-3">
                      <div className="text-sm font-medium text-gray-700">生成的命令预览:</div>
                      <div className="bg-gray-900 text-green-400 p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-32 overflow-y-auto">
                        {generatedCommand}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Toast 通知 */}
        {showToast && (
          <div className="fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50">
            {toastMessage}
          </div>
        )}
      </div>
    </div>
  );
};

export default TopazVideoAIConfigurator;
