import React, { useState, useCallback, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui';
import { Button } from '@/components/ui';
import { Input } from '@/components/ui';
import { Label } from '@/components/ui';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui';
import { Checkbox } from '@/components/ui';
import { Textarea } from '@/components/ui';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui';
import { Slider } from '@/components/ui';
import { Progress } from '@/components/ui';
import { Copy, Download, Play, FolderOpen, File, Terminal, RefreshCw, CheckCircle, XCircle, Clock } from 'lucide-react';
import { open, save } from '@tauri-apps/plugin-dialog';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';

interface CommandGeneratorProps {}

// 支持的视频格式
const SUPPORTED_VIDEO_FORMATS = [
  'mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'webm', 'm4v',
  '3gp', 'ts', 'mts', 'm2ts', 'asf', 'rm', 'rmvb', 'vob'
];

const SUPPORTED_OUTPUT_FORMATS = [
  'mp4', 'avi', 'mov', 'mkv', 'wmv', 'webm', 'm4v'
];

interface FilterSettings {
  // Frame Interpolation
  enableFI: boolean;
  fiModel: string;
  slowmo: number;
  rdt: number;
  
  // Upscale
  enableUpscale: boolean;
  upModel: string;
  scale: number;
  width: number;
  height: number;
  preblur: number;
  noise: number;
  details: number;
  halo: number;
  blur: number;
  compression: number;
  estimate: number;
  
  // Device settings
  device: string;
  vram: number;
  instances: number;
}

interface EncodingSettings {
  codec: string;
  profile: string;
  pixelFormat: string;
  gop: number;
  preset: string;
  tune: string;
  rateControl: string;
  qp: number;
  lookahead: number;
  spatialAQ: boolean;
  aqStrength: number;
  bitrate: number;
}

const CommandGenerator: React.FC<CommandGeneratorProps> = () => {
  const [inputFile, setInputFile] = useState('');
  const [outputFile, setOutputFile] = useState('');
  const [generatedCommand, setGeneratedCommand] = useState('');
  const [isExecuting, setIsExecuting] = useState(false);
  const [executionTaskId, setExecutionTaskId] = useState<string | null>(null);
  const [executionResult, setExecutionResult] = useState<string | null>(null);
  const [ffmpegStdout, setFfmpegStdout] = useState<string>('');
  const [ffmpegStderr, setFfmpegStderr] = useState<string>('');
  const [envCheckResult, setEnvCheckResult] = useState<any>(null);
  const [executionProgress, setExecutionProgress] = useState<{
    percentage: number;
    frame: number;
    fps: number;
    time: string;
    speed: string;
    bitrate: string;
  } | null>(null);
  
  const [filterSettings, setFilterSettings] = useState<FilterSettings>({
    enableFI: true,
    fiModel: 'apo-8',
    slowmo: 8,
    rdt: 0.01,
    
    enableUpscale: true,
    upModel: 'iris-3',
    scale: 1,
    width: 3840,
    height: 2176,
    preblur: 0,
    noise: 0,
    details: 0,
    halo: 0,
    blur: 0,
    compression: 0,
    estimate: 8,
    
    device: '-2',
    vram: 1,
    instances: 1,
  });
  
  const [encodingSettings, setEncodingSettings] = useState<EncodingSettings>({
    codec: 'h264_nvenc',
    profile: 'high',
    pixelFormat: 'yuv420p',
    gop: 30,
    preset: 'p7',
    tune: 'hq',
    rateControl: 'constqp',
    qp: 18,
    lookahead: 20,
    spatialAQ: true,
    aqStrength: 15,
    bitrate: 0,
  });

  // 动态模型列表（从 Tauri 后端获取，分组显示可用/缺失）
  const [, setAvailableModels] = useState<string[]>([]);
  const [allModels, setAllModels] = useState<{ value: string; label: string; downloaded: boolean; type: 'upscale' | 'interpolation' | 'other' }[]>([]);

  // 可用的模型选项
  const fiModels = allModels.filter(m => m.type === 'interpolation');

  const loadModels = useCallback(async () => {
    try {
      const res = await invoke<any>('list_available_tvai_models');
      const downloaded: string[] = res.downloaded || [];
      const all: { short_name: string; display_name?: string; model_type: string; is_downloaded: boolean }[] = res.all || [];
      const mapped = all.map(m => ({
        value: m.short_name,
        label: m.display_name || m.short_name,
        downloaded: m.is_downloaded,
        type: (m.model_type as 'upscale' | 'interpolation' | 'other')
      }));
      setAllModels(mapped);
      setAvailableModels(downloaded);
    } catch (e) {
      console.warn('加载模型信息失败:', e);
    }
  }, []);

  const isModelDownloaded = useCallback((name: string) => {
    return allModels.find(m => m.value === name)?.downloaded === true;
  }, [allModels]);

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

  const upscaleModels = allModels.filter(m => m.type === 'upscale');

  // 解析 short_name 版本号（apo-8 -> 8），无则返回 0
  const parseModelVersion = (name: string): number => {
    const m = name.match(/-(\d+)$/);
    return m ? parseInt(m[1], 10) : 0;
  };
  const familyOf = (name: string) => name.split('-')[0];
  const resolveModelName = (name: string, type: 'interpolation' | 'upscale' | 'other') => {
    if (!name) return name;
    if (name.includes('-')) return name; // 已是短名
    // 找到同家族且已下载的 short_name，优先版本号大的
    const family = familyOf(name);
    const candidates = allModels
      .filter(m => m.type === type && familyOf(m.value) === family && m.downloaded)
      .sort((a,b) => parseModelVersion(b.value) - parseModelVersion(a.value));
    return candidates[0]?.value || name; // 找不到则原样返回
  };

  const generateCommand = useCallback(() => {
    if (!inputFile) {
      alert('请选择输入文件或输入文件路径');
      return;
    }

    // 先规范化模型短名，避免出现 apo/iris 家族名
    const fiModel = filterSettings.enableFI ? resolveModelName(filterSettings.fiModel, 'interpolation') : '';
    const upModel = filterSettings.enableUpscale ? resolveModelName(filterSettings.upModel, 'upscale') : '';

    const parts: string[] = [];

    // 基础参数
    parts.push('ffmpeg');
    parts.push('"-hide_banner"');
    parts.push('"-i"');
    parts.push(`"${inputFile}"`);
    parts.push('"-sws_flags"');
    parts.push('"spline+accurate_rnd+full_chroma_int"');

    // 构建滤镜链
    const filters: string[] = [];

    // Frame Interpolation
    if (filterSettings.enableFI) {
      const fiParams = [
        `model=${fiModel}`,
        `slowmo=${filterSettings.slowmo}`,
        `rdt=${filterSettings.rdt}`,
        `device=${filterSettings.device}`,
        `vram=${filterSettings.vram}`,
        `instances=${filterSettings.instances}`,
      ];
      filters.push(`tvai_fi=${fiParams.join(':')}`);
    }

    // Upscale
    if (filterSettings.enableUpscale) {
      const upParams = [
        `model=${upModel}`,
        `scale=${filterSettings.scale}`,
        `w=${filterSettings.width}`,
        `h=${filterSettings.height}`,
        `preblur=${filterSettings.preblur}`,
        `noise=${filterSettings.noise}`,
        `details=${filterSettings.details}`,
        `halo=${filterSettings.halo}`,
        `blur=${filterSettings.blur}`,
        `compression=${filterSettings.compression}`,
        `estimate=${filterSettings.estimate}`,
        `device=${filterSettings.device}`,
        `vram=${filterSettings.vram}`,
        `instances=${filterSettings.instances}`,
      ];
      filters.push(`tvai_up=${upParams.join(':')}`);
    }

    if (filters.length > 0) {
      parts.push('"-filter_complex"');
      parts.push(`"${filters.join(',')}"`);
    }

    // 编码参数
    parts.push('"-c:v"');
    parts.push(`"${encodingSettings.codec}"`);
    parts.push('"-profile:v"');
    parts.push(`"${encodingSettings.profile}"`);
    parts.push('"-pix_fmt"');
    parts.push(`"${encodingSettings.pixelFormat}"`);
    parts.push('"-g"');
    parts.push(`"${encodingSettings.gop}"`);
    parts.push('"-preset"');
    parts.push(`"${encodingSettings.preset}"`);
    parts.push('"-tune"');
    parts.push(`"${encodingSettings.tune}"`);
    parts.push('"-rc"');
    parts.push(`"${encodingSettings.rateControl}"`);
    parts.push('"-qp"');
    parts.push(`"${encodingSettings.qp}"`);
    parts.push('"-rc-lookahead"');
    parts.push(`"${encodingSettings.lookahead}"`);

    if (encodingSettings.spatialAQ) {
      parts.push('"-spatial_aq"');
      parts.push('"1"');
      parts.push('"-aq-strength"');
      parts.push(`"${encodingSettings.aqStrength}"`);
    }

    parts.push('"-b:v"');
    parts.push(`"${encodingSettings.bitrate}"`);
    parts.push('"-an"');

    // 元数据
    parts.push('"-map_metadata"');
    parts.push('"0"');
    parts.push('"-map_metadata:s:v"');
    parts.push('"0:s:v"');
    parts.push('"-fps_mode:v"');
    parts.push('"passthrough"');
    parts.push('"-movflags"');
    parts.push('"frag_keyframe+empty_moov+delay_moov+use_metadata_tags+write_colr"');
    parts.push('"-bf"');
    parts.push('"0"');

    // 生成元数据描述
    const metadataDesc = generateMetadataDescription();
    parts.push('"-metadata"');
    parts.push(`"videoai=${metadataDesc}"`);

    // 输出文件
    const output = outputFile || generateOutputFilename(inputFile);
    parts.push(`"${output}"`);

    const command = parts.join(' ');
    setGeneratedCommand(command);
  }, [inputFile, outputFile, filterSettings, encodingSettings, allModels]);

  const generateMetadataDescription = () => {
    const parts: string[] = [];
    
    if (filterSettings.enableFI) {
      const slowmoPercent = Math.round(filterSettings.slowmo * 100);
      parts.push(`Slowmo ${slowmoPercent}% using ${filterSettings.fiModel} replacing duplicate frames`);
    }
    
    if (filterSettings.enableUpscale) {
      parts.push(`Enhanced using ${filterSettings.upModel}; mode: auto; reduce noise at ${filterSettings.noise}; reduce large grain at ${filterSettings.details}; revert compression at ${filterSettings.compression}; sharpen at ${filterSettings.blur}; dehalo at ${filterSettings.halo}; and anti-alias/deblur at ${filterSettings.preblur}`);
      
      if (filterSettings.scale !== 1 || filterSettings.width || filterSettings.height) {
        parts.push(`Changed resolution to ${filterSettings.width}x${filterSettings.height}`);
      }
    }
    
    return parts.join('. ');
  };

  const generateOutputFilename = (input: string) => {
    const timestamp = Date.now();
    const ext = input.split('.').pop();
    const baseName = input.replace(/\.[^/.]+$/, '');
    return `${baseName}_${timestamp}.${ext}`;
  };

  // 选择输入文件
  const handleSelectInputFile = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [{
          name: '视频文件',
          extensions: SUPPORTED_VIDEO_FORMATS
        }],
        title: '选择输入视频文件',
      });

      if (selected && typeof selected === 'string') {
        setInputFile(selected);
      }
    } catch (error) {
      console.error('选择输入文件失败:', error);
      alert('选择文件失败，请重试');
    }
  }, []);

  // 选择输出文件
  const handleSelectOutputFile = useCallback(async () => {
    try {
      const selected = await save({
        filters: [{
          name: '视频文件',
          extensions: SUPPORTED_OUTPUT_FORMATS
        }],
        title: '选择输出文件位置',
        defaultPath: inputFile ? generateOutputFilename(inputFile) : 'output.mp4',
      });

      if (selected && typeof selected === 'string') {
        setOutputFile(selected);
      }
    } catch (error) {
      console.error('选择输出文件失败:', error);
      alert('选择输出位置失败，请重试');
    }
  }, [inputFile]);

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(generatedCommand);
      alert('命令已复制到剪贴板');
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  const saveToFile = useCallback(async () => {
    if (!generatedCommand) {
      alert('请先生成命令');
      return;
    }

    try {
      const selected = await save({
        filters: [{
          name: '文本文件',
          extensions: ['txt', 'bat', 'sh']
        }],
        title: '保存 FFmpeg 命令',
        defaultPath: 'ffmpeg_command.txt',
      });

      if (selected) {
        // 在实际应用中，这里应该调用 Tauri 的文件写入 API
        // 目前使用浏览器的下载方式作为备选
        const blob = new Blob([generatedCommand], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = selected.split(/[/\\]/).pop() || 'ffmpeg_command.txt';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);

        alert('命令已保存');
      }
    } catch (error) {
      console.error('保存文件失败:', error);
      alert('保存失败，请重试');
    }
  }, [generatedCommand]);

  // 执行 FFmpeg 命令
  const executeCommand = useCallback(async () => {
    if (!generatedCommand) {
      alert('请先生成命令');
      return;
    }

    try {
      setIsExecuting(true);
      setExecutionResult(null);
      setExecutionProgress(null);
      setFfmpegStdout('');
      setFfmpegStderr('');

      // 解析命令参数
      const args = parseFFmpegCommand(generatedCommand);

      // 调用 Tauri 命令执行 FFmpeg
      console.log('Calling execute_ffmpeg_command with args:', args);
      const taskId = await invoke<string>('execute_ffmpeg_command', {
        commandArgs: args,
        useTopazFfmpeg: true, // 使用 Topaz FFmpeg 以支持 AI 滤镜
      });

      console.log('Received task ID:', taskId);
      setExecutionTaskId(taskId);
      setExecutionResult('命令已开始执行，任务ID: ' + taskId);

      // 这里可以添加任务状态监听
      // 实际应用中应该监听 'tvai_task_updated' 事件

    } catch (error) {
      console.error('执行命令失败:', error);
      setExecutionResult('执行失败: ' + (error as Error).message);
      setIsExecuting(false); // 只在出错时立即停止执行状态
    }
    // 不在 finally 中设置 isExecuting = false，让进度事件和完成事件来控制
  }, [generatedCommand]);

  // 从命令中提取 tvai 模型（model=xxx）
  const extractModelsFromCommand = (cmd: string): string[] => {
    const models: string[] = [];
    const re = /model=([^:\s,\"]+)/g;
    let m: RegExpExecArray | null;
    while ((m = re.exec(cmd)) !== null) {
      if (m[1]) models.push(m[1]);
    }
    // 去重
    return Array.from(new Set(models));
  };

  // 解析 FFmpeg 命令字符串为参数数组
  const parseFFmpegCommand = (command: string): string[] => {
    // 移除开头的 "ffmpeg"
    const withoutFFmpeg = command.replace(/^ffmpeg\s+/, '');

    // 简单的参数解析（处理引号）
    const args: string[] = [];
    let current = '';
    let inQuotes = false;
    let quoteChar = '';

    for (let i = 0; i < withoutFFmpeg.length; i++) {
      const char = withoutFFmpeg[i];

      if ((char === '"' || char === "'") && !inQuotes) {
        inQuotes = true;
        quoteChar = char;
      } else if (char === quoteChar && inQuotes) {
        inQuotes = false;
        quoteChar = '';
      } else if (char === ' ' && !inQuotes) {
        if (current.trim()) {
          args.push(current.trim());
          current = '';
        }
      } else {
        current += char;
      }
    }

    if (current.trim()) {
      args.push(current.trim());
    }

    return args;
  };

  // 监听 FFmpeg 执行完成事件
  useEffect(() => {
    const unlistenPromise = listen('ffmpeg_command_finished', (event) => {
      console.log('🏁 Received ffmpeg_command_finished event:', event.payload);
      const payload = event.payload as any;
      const { taskId, success, stdout, stderr } = payload || {};

      if (taskId && executionTaskId && taskId !== executionTaskId) {
        console.log('❌ Ignoring finished event for different task');
        return; // 只处理当前任务的事件
      }

      console.log('✅ Processing command finished event');
      setFfmpegStdout(stdout || '');
      setFfmpegStderr(stderr || '');
      setIsExecuting(false); // 在完成时停止执行状态

      // 保持最后的进度信息一段时间，然后清除
      setTimeout(() => {
        setExecutionProgress(null);
      }, 3000); // 3秒后清除进度信息

      if (success) {
        setExecutionResult('执行完成');
      } else {
        setExecutionResult('执行失败: ' + (stderr || '未知错误'));
      }
    });

    return () => {
      unlistenPromise.then((unlisten) => unlisten());
    };
  }, [executionTaskId]);

  // 监听 FFmpeg 进度事件
  useEffect(() => {
    console.log('Setting up ffmpeg_progress listener, executionTaskId:', executionTaskId);
    const unlistenPromise = listen('ffmpeg_progress', (event) => {
      console.log('🎯 Received ffmpeg_progress event:', event.payload);
      const payload = event.payload as any;
      const { taskId, progress, frame, fps, time, speed, bitrate } = payload || {};

      console.log('📋 Current state - executionTaskId:', executionTaskId, 'Event taskId:', taskId, 'isExecuting:', isExecuting);

      if (taskId && executionTaskId && taskId !== executionTaskId) {
        console.log('❌ Ignoring progress event for different task');
        return; // 只处理当前任务的事件
      }

      console.log('✅ Setting execution progress:', { progress, frame, fps, time, speed, bitrate });
      setExecutionProgress({
        percentage: progress || 0,
        frame: frame || 0,
        fps: fps || 0,
        time: time || '',
        speed: speed || '',
        bitrate: bitrate || '',
      });

      // 确保在收到进度时保持执行状态
      if (!isExecuting) {
        console.log('🔄 Setting isExecuting to true because we received progress');
        setIsExecuting(true);
      }
    });

    return () => {
      unlistenPromise.then((unlisten) => unlisten());
    };
  }, [executionTaskId, isExecuting]);

  return (
    <div className="container mx-auto p-6 space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Play className="w-5 h-5" />
            Topaz Video AI FFmpeg 命令生成器
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            <div>
              <Label htmlFor="input-file">输入文件路径</Label>
              <div className="flex gap-2">
                <Input
                  id="input-file"
                  value={inputFile}
                  onChange={(e) => setInputFile(e.target.value)}
                  placeholder="选择视频文件或手动输入路径"
                  className="flex-1"
                />
                <Button
                  type="button"
                  onClick={handleSelectInputFile}
                  variant="outline"
                  className="px-3"
                  title="浏览文件"
                >
                  <FolderOpen className="w-4 h-4" />
                </Button>
              </div>
            </div>
            <div>
              <Label htmlFor="output-file">输出文件路径 (可选)</Label>
              <div className="flex gap-2">
                <Input
                  id="output-file"
                  value={outputFile}
                  onChange={(e) => setOutputFile(e.target.value)}
                  placeholder="自动生成或选择保存位置"
                  className="flex-1"
                />
                <Button
                  type="button"
                  onClick={handleSelectOutputFile}
                  variant="outline"
                  className="px-3"
                  title="选择保存位置"
                >
                  <File className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </div>

          {/* 文件信息显示 */}
          {inputFile && (
            <Card className="mb-6">
              <CardContent className="pt-4">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                    <File className="w-4 h-4 text-blue-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900 truncate">
                      {inputFile.split(/[/\\]/).pop()}
                    </p>
                    <p className="text-xs text-gray-500 truncate">
                      {inputFile}
                    </p>
                  </div>
                  <Button
                    type="button"
                    onClick={() => setInputFile('')}
                    variant="ghost"
                    size="sm"
                    className="text-gray-400 hover:text-gray-600"
                  >
                    ✕
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}

          <Tabs defaultValue="filters" className="w-full">
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="filters">滤镜设置</TabsTrigger>
              <TabsTrigger value="encoding">编码设置</TabsTrigger>
              <TabsTrigger value="command">生成命令</TabsTrigger>
            </TabsList>
            
            <TabsContent value="filters" className="space-y-6">
              {/* Frame Interpolation 设置 */}
              <Card>
                <CardHeader>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="enable-fi"
                      checked={filterSettings.enableFI}
                      onCheckedChange={(checked) => 
                        setFilterSettings(prev => ({ ...prev, enableFI: checked as boolean }))
                      }
                    />
                    <Label htmlFor="enable-fi" className="text-lg font-semibold">
                      Frame Interpolation (帧插值)
                    </Label>
                  </div>
                </CardHeader>
                {filterSettings.enableFI && (
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <Label>模型</Label>
                        <Select
                          value={filterSettings.fiModel}
                          onValueChange={(value) =>
                            setFilterSettings(prev => ({ ...prev, fiModel: value }))
                          }
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <div className="px-2 py-1 text-xs text-gray-500">可用模型</div>
                            {fiModels.filter(m => m.downloaded).map(model => (
                              <SelectItem key={model.value} value={model.value}>
                                {model.label}
                              </SelectItem>
                            ))}
                            <div className="px-2 py-1 text-xs text-gray-400">缺失模型（需在 Topaz GUI 下载）</div>
                            {fiModels.filter(m => !m.downloaded).map(model => (
                              <SelectItem key={model.value} value={model.value}>
                                {model.label}（缺失）
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label>慢动作倍数: {filterSettings.slowmo}x</Label>
                        <Slider
                          value={[filterSettings.slowmo]}
                          onValueChange={([value]) => 
                            setFilterSettings(prev => ({ ...prev, slowmo: value }))
                          }
                          min={1}
                          max={16}
                          step={0.1}
                          className="mt-2"
                        />
                      </div>
                    </div>
                    <div>
                      <Label>重复帧检测阈值: {filterSettings.rdt}</Label>
                      <Slider
                        value={[filterSettings.rdt]}
                        onValueChange={([value]) => 
                          setFilterSettings(prev => ({ ...prev, rdt: value }))
                        }
                        min={0}
                        max={0.2}
                        step={0.001}
                        className="mt-2"
                      />
                    </div>
                  </CardContent>
                )}
              </Card>

              {/* Upscale 设置 */}
              <Card>
                <CardHeader>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="enable-upscale"
                      checked={filterSettings.enableUpscale}
                      onCheckedChange={(checked) => 
                        setFilterSettings(prev => ({ ...prev, enableUpscale: checked as boolean }))
                      }
                    />
                    <Label htmlFor="enable-upscale" className="text-lg font-semibold">
                      Upscale (视频增强)
                    </Label>
                  </div>
                </CardHeader>
                {filterSettings.enableUpscale && (
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <Label>模型</Label>
                        <Select
                          value={filterSettings.upModel}
                          onValueChange={(value) => 
                            setFilterSettings(prev => ({ ...prev, upModel: value }))
                          }
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {upscaleModels.map(model => (
                              <SelectItem key={model.value} value={model.value}>
                                {model.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label>缩放倍数: {filterSettings.scale}x</Label>
                        <Slider
                          value={[filterSettings.scale]}
                          onValueChange={([value]) => 
                            setFilterSettings(prev => ({ ...prev, scale: value }))
                          }
                          min={1}
                          max={4}
                          step={0.1}
                          className="mt-2"
                        />
                      </div>
                    </div>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="width">宽度</Label>
                        <Input
                          id="width"
                          type="number"
                          value={filterSettings.width}
                          onChange={(e) => 
                            setFilterSettings(prev => ({ ...prev, width: parseInt(e.target.value) || 0 }))
                          }
                        />
                      </div>
                      <div>
                        <Label htmlFor="height">高度</Label>
                        <Input
                          id="height"
                          type="number"
                          value={filterSettings.height}
                          onChange={(e) => 
                            setFilterSettings(prev => ({ ...prev, height: parseInt(e.target.value) || 0 }))
                          }
                        />
                      </div>
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                      <div>
                        <Label>预模糊: {filterSettings.preblur}</Label>
                        <Slider
                          value={[filterSettings.preblur]}
                          onValueChange={([value]) => 
                            setFilterSettings(prev => ({ ...prev, preblur: value }))
                          }
                          min={-1}
                          max={1}
                          step={0.1}
                          className="mt-2"
                        />
                      </div>
                      <div>
                        <Label>降噪: {filterSettings.noise}</Label>
                        <Slider
                          value={[filterSettings.noise]}
                          onValueChange={([value]) => 
                            setFilterSettings(prev => ({ ...prev, noise: value }))
                          }
                          min={-1}
                          max={1}
                          step={0.1}
                          className="mt-2"
                        />
                      </div>
                      <div>
                        <Label>细节: {filterSettings.details}</Label>
                        <Slider
                          value={[filterSettings.details]}
                          onValueChange={([value]) => 
                            setFilterSettings(prev => ({ ...prev, details: value }))
                          }
                          min={-1}
                          max={1}
                          step={0.1}
                          className="mt-2"
                        />
                      </div>
                      <div>
                        <Label>光晕: {filterSettings.halo}</Label>
                        <Slider
                          value={[filterSettings.halo]}
                          onValueChange={([value]) => 
                            setFilterSettings(prev => ({ ...prev, halo: value }))
                          }
                          min={-1}
                          max={1}
                          step={0.1}
                          className="mt-2"
                        />
                      </div>
                      <div>
                        <Label>锐化: {filterSettings.blur}</Label>
                        <Slider
                          value={[filterSettings.blur]}
                          onValueChange={([value]) => 
                            setFilterSettings(prev => ({ ...prev, blur: value }))
                          }
                          min={-1}
                          max={1}
                          step={0.1}
                          className="mt-2"
                        />
                      </div>
                      <div>
                        <Label>压缩修复: {filterSettings.compression}</Label>
                        <Slider
                          value={[filterSettings.compression]}
                          onValueChange={([value]) => 
                            setFilterSettings(prev => ({ ...prev, compression: value }))
                          }
                          min={-1}
                          max={1}
                          step={0.1}
                          className="mt-2"
                        />
                      </div>
                    </div>
                  </CardContent>
                )}
              </Card>

              {/* 设备设置 */}
              <Card>
                <CardHeader>
                  <CardTitle>设备设置</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                      <Label>设备</Label>
                      <Select
                        value={filterSettings.device}
                        onValueChange={(value) => 
                          setFilterSettings(prev => ({ ...prev, device: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="-2">自动选择</SelectItem>
                          <SelectItem value="-1">CPU</SelectItem>
                          <SelectItem value="0">GPU 0</SelectItem>
                          <SelectItem value="1">GPU 1</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>VRAM 使用率: {filterSettings.vram}</Label>
                      <Slider
                        value={[filterSettings.vram]}
                        onValueChange={([value]) => 
                          setFilterSettings(prev => ({ ...prev, vram: value }))
                        }
                        min={0.1}
                        max={1}
                        step={0.1}
                        className="mt-2"
                      />
                    </div>
                    <div>
                      <Label>实例数: {filterSettings.instances}</Label>
                      <Slider
                        value={[filterSettings.instances]}
                        onValueChange={([value]) => 
                          setFilterSettings(prev => ({ ...prev, instances: value }))
                        }
                        min={1}
                        max={3}
                        step={1}
                        className="mt-2"
                      />
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="encoding" className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle>编码设置</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <Label>编码器</Label>
                      <Select
                        value={encodingSettings.codec}
                        onValueChange={(value) => 
                          setEncodingSettings(prev => ({ ...prev, codec: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="h264_nvenc">H.264 NVENC</SelectItem>
                          <SelectItem value="hevc_nvenc">H.265 NVENC</SelectItem>
                          <SelectItem value="libx264">H.264 CPU</SelectItem>
                          <SelectItem value="libx265">H.265 CPU</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>配置文件</Label>
                      <Select
                        value={encodingSettings.profile}
                        onValueChange={(value) => 
                          setEncodingSettings(prev => ({ ...prev, profile: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="baseline">Baseline</SelectItem>
                          <SelectItem value="main">Main</SelectItem>
                          <SelectItem value="high">High</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <Label>预设</Label>
                      <Select
                        value={encodingSettings.preset}
                        onValueChange={(value) => 
                          setEncodingSettings(prev => ({ ...prev, preset: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="p1">P1 (最快)</SelectItem>
                          <SelectItem value="p4">P4 (平衡)</SelectItem>
                          <SelectItem value="p7">P7 (高质量)</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>调优</Label>
                      <Select
                        value={encodingSettings.tune}
                        onValueChange={(value) => 
                          setEncodingSettings(prev => ({ ...prev, tune: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="hq">高质量</SelectItem>
                          <SelectItem value="ll">低延迟</SelectItem>
                          <SelectItem value="ull">超低延迟</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <Label>QP 值: {encodingSettings.qp}</Label>
                      <Slider
                        value={[encodingSettings.qp]}
                        onValueChange={([value]) => 
                          setEncodingSettings(prev => ({ ...prev, qp: value }))
                        }
                        min={0}
                        max={51}
                        step={1}
                        className="mt-2"
                      />
                    </div>
                    <div>
                      <Label>GOP 大小: {encodingSettings.gop}</Label>
                      <Slider
                        value={[encodingSettings.gop]}
                        onValueChange={([value]) => 
                          setEncodingSettings(prev => ({ ...prev, gop: value }))
                        }
                        min={1}
                        max={300}
                        step={1}
                        className="mt-2"
                      />
                    </div>
                  </div>

                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="spatial-aq"
                      checked={encodingSettings.spatialAQ}
                      onCheckedChange={(checked) => 
                        setEncodingSettings(prev => ({ ...prev, spatialAQ: checked as boolean }))
                      }
                    />
                    <Label htmlFor="spatial-aq">启用空间自适应量化</Label>
                  </div>

                  {encodingSettings.spatialAQ && (
                    <div>
                      <Label>AQ 强度: {encodingSettings.aqStrength}</Label>
                      <Slider
                        value={[encodingSettings.aqStrength]}
                        onValueChange={([value]) => 
                          setEncodingSettings(prev => ({ ...prev, aqStrength: value }))
                        }
                        min={1}
                        max={15}
                        step={1}
                        className="mt-2"
                      />
                    </div>
                  )}
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="command" className="space-y-6">
              <div className="flex gap-2 mb-4">
                <Button onClick={generateCommand} className="flex-1">
                  生成命令
                </Button>
                <Button
                  onClick={async () => {
                    try {
                      const modelsInCommand = extractModelsFromCommand(generatedCommand);
                      const result = await invoke<any>('validate_tvai_models', { requiredModels: modelsInCommand });
                      if (result.missing && result.missing.length > 0) {
                        setExecutionResult(`缺失模型: ${result.missing.join(', ')}。已提供替代建议，可一键替换。`);
                        setFfmpegStdout(JSON.stringify(result.suggestions, null, 2));
                      } else {
                        setExecutionResult('所有模型均已可用');
                        setFfmpegStdout('');
                      }
                    } catch (e:any) {
                      setExecutionResult('检测失败: ' + (e.message || String(e)));
                    }
                  }}
                  variant="outline"
                  disabled={!generatedCommand}
                >
                  检查模型
                </Button>
                <Button
                  onClick={async () => {
                    try {
                      const envCheck = await invoke<any>('check_topaz_environment');
                      setEnvCheckResult(envCheck);
                      setExecutionResult('环境变量检查完成');
                      setFfmpegStdout(JSON.stringify(envCheck, null, 2));
                      setFfmpegStderr('');
                    } catch (e:any) {
                      setExecutionResult('环境检查失败: ' + (e.message || String(e)));
                    }
                  }}
                  variant="outline"
                >
                  <CheckCircle className="w-4 h-4 mr-2" />
                  检查环境
                </Button>
                <Button
                  onClick={() => {
                    // 测试进度事件
                    const testTaskId = 'test_' + Date.now();
                    console.log('🧪 Testing progress with taskId:', testTaskId);
                    setExecutionTaskId(testTaskId);
                    setIsExecuting(true);

                    // 模拟进度更新
                    let progress = 0;
                    const interval = setInterval(() => {
                      progress += 10;
                      console.log('🧪 Setting test progress:', progress);
                      setExecutionProgress({
                        percentage: progress,
                        frame: progress * 10,
                        fps: 25.0,
                        time: `00:00:${String(Math.floor(progress / 10)).padStart(2, '0')}.00`,
                        speed: '1.0x',
                        bitrate: '1000kbits/s',
                      });

                      if (progress >= 100) {
                        clearInterval(interval);
                        setIsExecuting(false);
                        setTimeout(() => setExecutionProgress(null), 3000);
                        setExecutionResult('测试完成');
                      }
                    }, 500);
                  }}
                  variant="outline"
                >
                  测试进度条
                </Button>
                <Button
                  onClick={() => {
                    console.log('🔍 Current state debug:');
                    console.log('- isExecuting:', isExecuting);
                    console.log('- executionTaskId:', executionTaskId);
                    console.log('- executionProgress:', executionProgress);
                    console.log('- executionResult:', executionResult);
                  }}
                  variant="outline"
                >
                  调试状态
                </Button>
                <Button
                  onClick={async () => {
                    try {
                      const debug = await invoke<any>('debug_model_detection');
                      setExecutionResult('模型调试信息已生成');
                      setFfmpegStdout(JSON.stringify(debug, null, 2));
                      setFfmpegStderr('');
                    } catch (e:any) {
                      setExecutionResult('调试失败: ' + (e.message || String(e)));
                    }
                  }}
                  variant="outline"
                >
                  调试模型
                </Button>
                <Button
                  onClick={() => {
                    try {
                      const modelsInCommand = extractModelsFromCommand(generatedCommand);
                      // 这里简单调用一次 validate 以获取建议
                      invoke<any>('validate_tvai_models', { requiredModels: modelsInCommand }).then((res) => {
                        let cmd = generatedCommand;
                        const suggestions = res?.suggestions || {};
                        for (const miss of res?.missing || []) {
                          const repl = suggestions[miss]?.[0];
                          if (repl) {
                            cmd = cmd.replace(new RegExp(`model=${miss}\b`, 'g'), `model=${repl}`);
                          }
                        }
                        setGeneratedCommand(cmd);
                        setExecutionResult('已用建议替代缺失模型');
                      });
                    } catch {}
                  }}
                  variant="outline"
                  disabled={!generatedCommand}
                >
                  一键替代
                </Button>
                <Button
                  onClick={executeCommand}
                  variant="default"
                  disabled={!generatedCommand || isExecuting}
                  className="bg-green-600 hover:bg-green-700"
                >
                  <Terminal className="w-4 h-4 mr-2" />
                  {isExecuting ? '执行中...' : '执行命令'}
                </Button>
                <Button onClick={copyToClipboard} variant="outline" disabled={!generatedCommand}>
                  <Copy className="w-4 h-4 mr-2" />
                  复制
                </Button>
                <Button onClick={saveToFile} variant="outline" disabled={!generatedCommand}>
                  <Download className="w-4 h-4 mr-2" />
                  保存
                </Button>
              </div>

              <Card>
                <CardHeader>
                  <CardTitle>生成的 FFmpeg 命令</CardTitle>
                </CardHeader>
                <CardContent>
                  <Textarea
                    value={generatedCommand}
                    onChange={(e) => setGeneratedCommand(e.target.value)}
                    className="min-h-[200px] font-mono text-sm"
                    placeholder="可手动编辑生成的 FFmpeg 命令..."
                  />
                </CardContent>
              </Card>

              {/* 执行进度显示 */}
              {isExecuting && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Terminal className="w-5 h-5 text-blue-500" />
                      正在执行 FFmpeg 命令
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {executionProgress ? (
                      <>
                        {/* 进度条 */}
                        <Progress
                          value={executionProgress.percentage}
                          showValue={true}
                          size="md"
                          color="blue"
                        />

                        {/* 详细信息 */}
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                          <div className="bg-gray-50 p-2 rounded">
                            <div className="text-gray-500">帧数</div>
                            <div className="font-mono">{executionProgress.frame}</div>
                          </div>
                          <div className="bg-gray-50 p-2 rounded">
                            <div className="text-gray-500">FPS</div>
                            <div className="font-mono">{executionProgress.fps.toFixed(1)}</div>
                          </div>
                          <div className="bg-gray-50 p-2 rounded">
                            <div className="text-gray-500">时间</div>
                            <div className="font-mono">{executionProgress.time}</div>
                          </div>
                          <div className="bg-gray-50 p-2 rounded">
                            <div className="text-gray-500">速度</div>
                            <div className="font-mono">{executionProgress.speed}</div>
                          </div>
                        </div>

                        {executionProgress.bitrate && (
                          <div className="text-sm text-gray-600">
                            <span className="font-medium">码率:</span> {executionProgress.bitrate}
                          </div>
                        )}
                      </>
                    ) : (
                      <div className="flex items-center gap-3">
                        <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
                        <span className="text-gray-600">正在启动 FFmpeg...</span>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}

              {/* 环境变量设置指导 */}
              {envCheckResult && envCheckResult.recommendations && (
                envCheckResult.recommendations.should_set_tvai_model_dir ||
                envCheckResult.recommendations.should_set_tvai_model_data_dir ||
                envCheckResult.recommendations.should_add_to_path
              ) && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <XCircle className="w-5 h-5 text-orange-500" />
                      需要设置环境变量
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
                      <h4 className="font-medium text-orange-800 mb-2">设置步骤：</h4>
                      <ol className="list-decimal list-inside space-y-2 text-sm text-orange-700">
                        <li>打开 Topaz Video AI 应用程序并登录账号</li>
                        <li>按快捷键 <kbd className="bg-orange-100 px-1 rounded">Ctrl+Shift+T</kbd> 打开命令窗口</li>
                        <li>这会自动设置模型目录到环境变量</li>
                        <li>如果自动设置失败，请手动设置以下环境变量：</li>
                      </ol>

                      {envCheckResult.recommendations.should_set_tvai_model_dir && (
                        <div className="mt-3 p-2 bg-white rounded border">
                          <strong>TVAI_MODEL_DIR:</strong> {envCheckResult.recommendations.suggested_tvai_model_dir}
                        </div>
                      )}

                      {envCheckResult.recommendations.should_set_tvai_model_data_dir && (
                        <div className="mt-2 p-2 bg-white rounded border">
                          <strong>TVAI_MODEL_DATA_DIR:</strong> {envCheckResult.recommendations.suggested_tvai_model_dir}
                        </div>
                      )}

                      {envCheckResult.recommendations.should_add_to_path && (
                        <div className="mt-2 p-2 bg-white rounded border">
                          <strong>PATH 添加:</strong> {envCheckResult.recommendations.suggested_path_addition}
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* 执行结果显示 */}
              {(executionResult || ffmpegStdout || ffmpegStderr) && (
                <Card>
                  <CardHeader>
                    <CardTitle>执行结果与日志</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    {executionResult && (
                      <div className={`p-3 rounded-lg text-sm ${
                        executionResult.includes('失败') || executionResult.includes('错误')
                          ? 'bg-red-50 text-red-800 border border-red-200'
                          : 'bg-green-50 text-green-800 border border-green-200'
                      }`}>
                        {executionResult}
                      </div>
                    )}
                    {executionTaskId && (
                      <div className="text-xs text-gray-500">
                        任务ID: {executionTaskId}
                      </div>
                    )}

                    {(ffmpegStdout || ffmpegStderr) && (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                          <div className="text-sm font-medium text-gray-700 mb-1">FFmpeg 输出(stdout)</div>
                          <pre className="bg-gray-900 text-green-200 text-xs p-3 rounded-lg overflow-auto max-h-60 whitespace-pre-wrap break-words border border-gray-700">
{ffmpegStdout || '无'}
                          </pre>
                        </div>
                        <div>
                          <div className="text-sm font-medium text-gray-700 mb-1">FFmpeg 错误(stderr)</div>
                          <pre className="bg-gray-900 text-red-200 text-xs p-3 rounded-lg overflow-auto max-h-60 whitespace-pre-wrap break-words border border-gray-700">
{ffmpegStderr || '无'}
                          </pre>
                        </div>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}

              {generatedCommand && (
                <Card>
                  <CardHeader>
                    <CardTitle>命令说明</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2 text-sm">
                      {filterSettings.enableFI && (
                        <p>• <strong>帧插值</strong>: 使用 {filterSettings.fiModel} 模型，{filterSettings.slowmo}x 慢动作</p>
                      )}
                      {filterSettings.enableUpscale && (
                        <p>• <strong>视频增强</strong>: 使用 {filterSettings.upModel} 模型，输出分辨率 {filterSettings.width}x{filterSettings.height}</p>
                      )}
                      <p>• <strong>编码</strong>: {encodingSettings.codec} 编码器，QP={encodingSettings.qp}</p>
                      <p>• <strong>设备</strong>: {filterSettings.device === '-2' ? '自动选择' : filterSettings.device === '-1' ? 'CPU' : `GPU ${filterSettings.device}`}</p>
                      <p>• <strong>执行</strong>: 点击"执行命令"按钮可直接在 Topaz Video AI 环境中运行</p>
                    </div>
                  </CardContent>
                </Card>
              )}
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    </div>
  );
};

export default CommandGenerator;
