import React from 'react';
import { Settings, Clock, Image as ImageIcon, Sliders } from 'lucide-react';
import {
  ThumbnailConfig,
  TimePoint,
  SizePreset,
  ImageFormat,
  SIZE_PRESET_DIMENSIONS
} from '../../types/thumbnail';
import { CustomSelect } from '../CustomSelect';

interface ThumbnailConfigPanelProps {
  config: ThumbnailConfig;
  onChange: (config: ThumbnailConfig) => void;
}

/**
 * 缩略图配置面板组件
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
export const ThumbnailConfigPanel: React.FC<ThumbnailConfigPanelProps> = ({
  config,
  onChange,
}) => {
  // 更新配置的辅助函数
  const updateConfig = (updates: Partial<ThumbnailConfig>) => {
    onChange({ ...config, ...updates });
  };

  // 更新时间点配置
  const updateTimePoints = (timePoints: TimePoint[]) => {
    updateConfig({ time_points: timePoints });
  };

  // 更新尺寸配置
  const updateSize = (updates: Partial<ThumbnailConfig['size']>) => {
    updateConfig({
      size: { ...config.size, ...updates }
    });
  };

  // 处理预设尺寸变化
  const handlePresetChange = (preset: string) => {
    const sizePreset = preset as SizePreset;
    if (sizePreset === SizePreset.Custom) {
      updateSize({ preset: sizePreset });
    } else {
      const [width, height] = SIZE_PRESET_DIMENSIONS[sizePreset];
      updateSize({ width, height, preset: sizePreset });
    }
  };

  // 添加时间点
  const addTimePoint = () => {
    const newTimePoint: TimePoint = { Percentage: 0.5 };
    updateTimePoints([...config.time_points, newTimePoint]);
  };

  // 删除时间点
  const removeTimePoint = (index: number) => {
    const newTimePoints = config.time_points.filter((_, i) => i !== index);
    updateTimePoints(newTimePoints);
  };

  // 更新时间点
  const updateTimePoint = (index: number, timePoint: TimePoint) => {
    const newTimePoints = [...config.time_points];
    newTimePoints[index] = timePoint;
    updateTimePoints(newTimePoints);
  };

  // 渲染时间点配置
  const renderTimePointConfig = (timePoint: TimePoint, index: number) => {
    const timePointType = Object.keys(timePoint)[0] as keyof TimePoint;
    const timePointValue = Object.values(timePoint)[0];

    return (
      <div key={index} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
        <div className="flex-1 grid grid-cols-2 gap-3">
          <CustomSelect
            value={timePointType}
            onChange={(type) => {
              let newTimePoint: TimePoint;
              switch (type) {
                case 'Fixed':
                  newTimePoint = { Fixed: 5.0 };
                  break;
                case 'Percentage':
                  newTimePoint = { Percentage: 0.5 };
                  break;
                case 'SmartDetection':
                  newTimePoint = { SmartDetection: 5 };
                  break;
                default:
                  newTimePoint = { Percentage: 0.5 };
              }
              updateTimePoint(index, newTimePoint);
            }}
            options={[
              { value: 'Fixed', label: '固定时间' },
              { value: 'Percentage', label: '百分比' },
              { value: 'SmartDetection', label: '智能检测' },
            ]}
            className="text-sm"
          />

          <div className="flex items-center gap-2">
            <input
              type="number"
              value={Array.isArray(timePointValue) ? timePointValue[0] : timePointValue}
              onChange={(e) => {
                const value = parseFloat(e.target.value);
                let newTimePoint: TimePoint;
                switch (timePointType) {
                  case 'Fixed':
                    newTimePoint = { Fixed: value };
                    break;
                  case 'Percentage':
                    newTimePoint = { Percentage: Math.max(0, Math.min(1, value)) };
                    break;
                  case 'SmartDetection':
                    newTimePoint = { SmartDetection: Math.max(1, Math.floor(value)) };
                    break;
                  default:
                    newTimePoint = { Percentage: 0.5 };
                }
                updateTimePoint(index, newTimePoint);
              }}
              min={timePointType === 'Percentage' ? 0 : timePointType === 'SmartDetection' ? 1 : 0}
              max={timePointType === 'Percentage' ? 1 : undefined}
              step={timePointType === 'Percentage' ? 0.1 : timePointType === 'SmartDetection' ? 1 : 0.1}
              className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm"
            />
            <span className="text-sm text-gray-500">
              {timePointType === 'Fixed' ? '秒' : 
               timePointType === 'Percentage' ? '%' : '帧'}
            </span>
          </div>
        </div>

        <button
          onClick={() => removeTimePoint(index)}
          className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
          disabled={config.time_points.length <= 1}
        >
          ×
        </button>
      </div>
    );
  };

  return (
    <div className="card p-6 space-y-6">
      <h3 className="text-lg font-semibold flex items-center gap-2">
        <Settings className="w-5 h-5" />
        缩略图配置
      </h3>

      {/* 时间点配置 */}
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
            <Clock className="w-4 h-4" />
            时间点设置
          </label>
          <button
            onClick={addTimePoint}
            className="px-3 py-1 text-sm bg-primary-100 text-primary-600 rounded-lg hover:bg-primary-200 transition-colors"
          >
            + 添加时间点
          </button>
        </div>

        <div className="space-y-3">
          {config.time_points.map((timePoint, index) => 
            renderTimePointConfig(timePoint, index)
          )}
        </div>
      </div>

      {/* 尺寸配置 */}
      <div className="space-y-4">
        <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
          <ImageIcon className="w-4 h-4" />
          缩略图尺寸
        </label>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-xs text-gray-500 mb-1">预设尺寸</label>
            <CustomSelect
              value={config.size.preset || SizePreset.Custom}
              onChange={handlePresetChange}
              options={[
                { value: SizePreset.Tiny, label: '微小 (160×120)' },
                { value: SizePreset.Small, label: '小 (320×240)' },
                { value: SizePreset.Medium, label: '中 (640×480)' },
                { value: SizePreset.Large, label: '大 (1280×720)' },
                { value: SizePreset.FullHD, label: '全高清 (1920×1080)' },
                { value: SizePreset.Custom, label: '自定义' },
              ]}
            />
          </div>

          <div className="grid grid-cols-2 gap-2">
            <div>
              <label className="block text-xs text-gray-500 mb-1">宽度</label>
              <input
                type="number"
                value={config.size.width}
                onChange={(e) => updateSize({ width: parseInt(e.target.value), preset: SizePreset.Custom })}
                min={1}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
              />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">高度</label>
              <input
                type="number"
                value={config.size.height}
                onChange={(e) => updateSize({ height: parseInt(e.target.value), preset: SizePreset.Custom })}
                min={1}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
              />
            </div>
          </div>
        </div>
      </div>

      {/* 格式和质量配置 */}
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">输出格式</label>
          <CustomSelect
            value={config.format}
            onChange={(format) => updateConfig({ format: format as ImageFormat })}
            options={[
              { value: ImageFormat.Jpg, label: 'JPEG' },
              { value: ImageFormat.Png, label: 'PNG' },
              { value: ImageFormat.WebP, label: 'WebP' },
            ]}
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
            <Sliders className="w-4 h-4" />
            质量 ({config.quality}%)
          </label>
          <input
            type="range"
            min={1}
            max={100}
            value={config.quality}
            onChange={(e) => updateConfig({ quality: parseInt(e.target.value) })}
            className="w-full"
          />
        </div>
      </div>

      {/* 输出配置 */}
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">输出目录</label>
          <input
            type="text"
            value={config.output_dir}
            onChange={(e) => updateConfig({ output_dir: e.target.value })}
            placeholder="thumbnails"
            className="w-full px-3 py-2 border border-gray-300 rounded-lg"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">文件命名模式</label>
          <input
            type="text"
            value={config.naming_pattern}
            onChange={(e) => updateConfig({ naming_pattern: e.target.value })}
            placeholder="{filename}_{timestamp}.{ext}"
            className="w-full px-3 py-2 border border-gray-300 rounded-lg"
          />
          <p className="text-xs text-gray-500 mt-1">
            可用变量: {'{filename}'}, {'{timestamp}'}, {'{index}'}, {'{ext}'}
          </p>
        </div>

        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            checked={config.preserve_aspect_ratio}
            onChange={(e) => updateConfig({ preserve_aspect_ratio: e.target.checked })}
            className="rounded"
          />
          <span className="text-sm">保持宽高比</span>
        </label>
      </div>
    </div>
  );
};
