import React, { useState, useCallback } from 'react';
import {
  Settings,
  FolderOpen,
  Image,
  Sliders,
  Clock,
  Percent,
  Hash,
  Save,
  RotateCcw,
  Info
} from 'lucide-react';
import { open } from '@tauri-apps/plugin-dialog';

import {
  FrameExtractionConfig,
  FrameExtractionPreset,
  FrameType,
  ImageFormat,
  TimePoint,
  VideoFileInfo
} from '../../types/frame-extractor';

interface FrameExtractionConfigPanelProps {
  config: FrameExtractionConfig;
  onConfigChange: (config: FrameExtractionConfig) => void;
  onApplyPreset: (presetId: string) => void;
  presets: FrameExtractionPreset[];
  currentVideo?: VideoFileInfo;
  currentTime?: number;
  onTimeChange?: (time: number) => void;
}

/**
 * 关键帧提取配置面板组件
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
export const FrameExtractionConfigPanel: React.FC<FrameExtractionConfigPanelProps> = ({
  config,
  onConfigChange,
  onApplyPreset,
  presets,
  currentVideo,
  currentTime,
  onTimeChange
}) => {
  const [customTimePoints, setCustomTimePoints] = useState<string>('');

  // 格式化时长显示
  const formatDuration = (seconds: number): string => {
    if (isNaN(seconds)) return '00:00';
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);

    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // 更新配置
  const updateConfig = useCallback((updates: Partial<FrameExtractionConfig>) => {
    onConfigChange({ ...config, ...updates });
  }, [config, onConfigChange]);

  // 选择输出目录
  const handleSelectOutputDirectory = useCallback(async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
        title: '选择输出目录',
      });

      if (selected && typeof selected === 'string') {
        updateConfig({ output_directory: selected });
      }
    } catch (error) {
      console.error('选择输出目录失败:', error);
    }
  }, [updateConfig]);

  // 处理帧类型变化
  const handleFrameTypeChange = useCallback((frameType: FrameType) => {
    const updates: Partial<FrameExtractionConfig> = { frame_type: frameType };
    
    // 根据帧类型设置默认值
    switch (frameType) {
      case FrameType.First:
      case FrameType.Last:
        updates.custom_time = undefined;
        updates.time_points = undefined;
        break;
      case FrameType.Custom:
        updates.custom_time = 0;
        updates.time_points = undefined;
        break;
      case FrameType.Multiple:
        updates.custom_time = undefined;
        updates.time_points = [];
        break;
    }
    
    updateConfig(updates);
  }, [updateConfig]);

  // 处理多时间点输入
  const handleTimePointsChange = useCallback((value: string) => {
    setCustomTimePoints(value);
    
    if (config.frame_type === FrameType.Multiple) {
      try {
        const points = value.split(',').map(p => p.trim()).filter(p => p);
        const timePoints: TimePoint[] = points.map(point => {
          if (point.endsWith('%')) {
            const percentage = parseFloat(point.slice(0, -1)) / 100;
            return { type: 'percentage', value: percentage };
          } else if (point.includes('f')) {
            const frameNumber = parseInt(point.replace('f', ''));
            return { type: 'frame', value: frameNumber };
          } else {
            const seconds = parseFloat(point);
            return { type: 'seconds', value: seconds };
          }
        });
        
        updateConfig({ time_points: timePoints });
      } catch (error) {
        console.error('解析时间点失败:', error);
      }
    }
  }, [config.frame_type, updateConfig]);

  return (
    <div className="bg-white rounded-lg shadow-sm border p-6 space-y-6">
      <div className="flex items-center gap-3 mb-6">
        <Settings className="w-5 h-5 text-blue-600" />
        <h3 className="text-lg font-semibold text-gray-900">提取配置</h3>
      </div>

      {/* 预设配置 */}
      <div className="space-y-3">
        <label className="block text-sm font-medium text-gray-700">
          预设配置
        </label>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
          {presets.map((preset) => (
            <button
              key={preset.id}
              onClick={() => onApplyPreset(preset.id)}
              className="p-3 text-left border rounded-lg hover:bg-gray-50 transition-colors"
            >
              <div className="font-medium text-sm text-gray-900">{preset.name}</div>
              <div className="text-xs text-gray-500 mt-1">{preset.description}</div>
            </button>
          ))}
        </div>
      </div>

      {/* 帧类型选择 */}
      <div className="space-y-3">
        <label className="block text-sm font-medium text-gray-700">
          提取类型
        </label>
        <div className="grid grid-cols-2 gap-2">
          {Object.values(FrameType).map((type) => (
            <button
              key={type}
              onClick={() => handleFrameTypeChange(type)}
              className={`p-3 text-center border rounded-lg transition-colors ${
                config.frame_type === type
                  ? 'border-blue-500 bg-blue-50 text-blue-700'
                  : 'border-gray-200 hover:bg-gray-50'
              }`}
            >
              <div className="font-medium text-sm">
                {type === FrameType.First && '第一帧'}
                {type === FrameType.Last && '最后一帧'}
                {type === FrameType.Custom && '自定义时间'}
                {type === FrameType.Multiple && '多个时间点'}
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* 自定义时间输入 */}
      {config.frame_type === FrameType.Custom && (
        <div className="space-y-3">
          <label className="block text-sm font-medium text-gray-700">
            自定义时间 (秒)
          </label>
          <div className="relative">
            <Clock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="number"
              min="0"
              step="0.1"
              max={currentVideo?.duration || undefined}
              value={config.custom_time || 0}
              onChange={(e) => {
                const time = parseFloat(e.target.value) || 0;
                updateConfig({ custom_time: time });
                onTimeChange?.(time);
              }}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="输入时间（秒）"
            />
          </div>
          {currentVideo && (
            <div className="flex items-center justify-between text-sm text-gray-500">
              <span>视频总时长: {formatDuration(currentVideo.duration)}</span>
              {currentTime !== undefined && (
                <button
                  onClick={() => {
                    updateConfig({ custom_time: currentTime });
                  }}
                  className="text-blue-600 hover:text-blue-800 font-medium"
                >
                  使用当前播放时间 ({formatDuration(currentTime)})
                </button>
              )}
            </div>
          )}
        </div>
      )}

      {/* 多时间点输入 */}
      {config.frame_type === FrameType.Multiple && (
        <div className="space-y-3">
          <label className="block text-sm font-medium text-gray-700">
            多个时间点
          </label>
          <textarea
            value={customTimePoints}
            onChange={(e) => handleTimePointsChange(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            rows={3}
            placeholder="输入时间点，用逗号分隔&#10;支持格式：&#10;- 秒数：1.5, 10, 30&#10;- 百分比：25%, 50%, 75%&#10;- 帧数：100f, 500f, 1000f"
          />
          <div className="flex items-start gap-2 text-xs text-gray-500">
            <Info className="w-3 h-3 mt-0.5 flex-shrink-0" />
            <div>
              支持多种格式：秒数 (1.5)、百分比 (50%)、帧数 (100f)
            </div>
          </div>
        </div>
      )}

      {/* 输出格式设置 */}
      <div className="space-y-3">
        <label className="block text-sm font-medium text-gray-700">
          输出格式
        </label>
        <div className="grid grid-cols-4 gap-2">
          {Object.values(ImageFormat).map((format) => (
            <button
              key={format}
              onClick={() => updateConfig({
                output_format: { ...config.output_format, format }
              })}
              className={`p-2 text-center border rounded-lg transition-colors ${
                config.output_format.format === format
                  ? 'border-blue-500 bg-blue-50 text-blue-700'
                  : 'border-gray-200 hover:bg-gray-50'
              }`}
            >
              <div className="font-medium text-xs uppercase">{format}</div>
            </button>
          ))}
        </div>
      </div>

      {/* 质量设置 */}
      <div className="space-y-3">
        <label className="block text-sm font-medium text-gray-700">
          图片质量: {config.output_format.quality}
        </label>
        <div className="relative">
          <Sliders className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="range"
            min="1"
            max="100"
            value={config.output_format.quality}
            onChange={(e) => updateConfig({
              output_format: {
                ...config.output_format,
                quality: parseInt(e.target.value)
              }
            })}
            className="w-full pl-10 pr-4"
          />
        </div>
        <div className="flex justify-between text-xs text-gray-500">
          <span>低质量</span>
          <span>高质量</span>
        </div>
      </div>

      {/* 输出尺寸设置 */}
      <div className="space-y-3">
        <label className="block text-sm font-medium text-gray-700">
          输出尺寸
        </label>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-xs text-gray-500 mb-1">宽度 (像素)</label>
            <input
              type="number"
              min="1"
              value={config.output_size?.width || ''}
              onChange={(e) => updateConfig({
                output_size: {
                  maintain_aspect_ratio: true,
                  ...config.output_size,
                  width: e.target.value ? parseInt(e.target.value) : undefined
                }
              })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="自动"
            />
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">高度 (像素)</label>
            <input
              type="number"
              min="1"
              value={config.output_size?.height || ''}
              onChange={(e) => updateConfig({
                output_size: {
                  maintain_aspect_ratio: true,
                  ...config.output_size,
                  height: e.target.value ? parseInt(e.target.value) : undefined
                }
              })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="自动"
            />
          </div>
        </div>
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            checked={config.output_size?.maintain_aspect_ratio ?? true}
            onChange={(e) => updateConfig({
              output_size: {
                ...config.output_size,
                maintain_aspect_ratio: e.target.checked
              }
            })}
            className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
          />
          <span className="text-sm text-gray-700">保持宽高比</span>
        </label>
      </div>

      {/* 输出目录设置 */}
      <div className="space-y-3">
        <label className="block text-sm font-medium text-gray-700">
          输出目录
        </label>
        <div className="flex gap-2">
          <input
            type="text"
            value={config.output_directory}
            onChange={(e) => updateConfig({ output_directory: e.target.value })}
            className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            placeholder="选择输出目录"
          />
          <button
            onClick={handleSelectOutputDirectory}
            className="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
          >
            <FolderOpen className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* 文件名模式 */}
      <div className="space-y-3">
        <label className="block text-sm font-medium text-gray-700">
          文件名模式
        </label>
        <input
          type="text"
          value={config.filename_pattern}
          onChange={(e) => updateConfig({ filename_pattern: e.target.value })}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          placeholder="文件名模式"
        />
        <div className="flex items-start gap-2 text-xs text-gray-500">
          <Info className="w-3 h-3 mt-0.5 flex-shrink-0" />
          <div>
            支持变量：{'{name}'} (视频名称)、{'{frame_type}'} (帧类型)、{'{timestamp}'} (时间戳)、{'{index}'} (索引)
          </div>
        </div>
      </div>

      {/* 其他选项 */}
      <div className="space-y-3">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            checked={config.overwrite_existing}
            onChange={(e) => updateConfig({ overwrite_existing: e.target.checked })}
            className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
          />
          <span className="text-sm text-gray-700">覆盖已存在的文件</span>
        </label>
      </div>
    </div>
  );
};
