import React, { useState, useCallback, useRef, useEffect } from 'react';
import { ColorHSV, ColorPickerProps } from '../../types/outfitSearch';
import { ColorUtils } from '../../utils/colorUtils';

/**
 * HSV颜色选择器组件
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const ColorPicker: React.FC<ColorPickerProps> = ({
  color,
  onChange,
  disabled = false,
}) => {
  const [isDragging, setIsDragging] = useState(false);
  const [dragTarget, setDragTarget] = useState<'hue' | 'saturation' | 'value' | null>(null);
  const hueRef = useRef<HTMLDivElement>(null);
  const saturationRef = useRef<HTMLDivElement>(null);
  const valueRef = useRef<HTMLDivElement>(null);

  // 处理鼠标按下事件
  const handleMouseDown = useCallback((target: 'hue' | 'saturation' | 'value') => {
    if (disabled) return;
    setIsDragging(true);
    setDragTarget(target);
  }, [disabled]);

  // 处理鼠标移动事件
  const handleMouseMove = useCallback((e: MouseEvent) => {
    if (!isDragging || !dragTarget || disabled) return;

    const rect = (() => {
      switch (dragTarget) {
        case 'hue':
          return hueRef.current?.getBoundingClientRect();
        case 'saturation':
          return saturationRef.current?.getBoundingClientRect();
        case 'value':
          return valueRef.current?.getBoundingClientRect();
        default:
          return null;
      }
    })();

    if (!rect) return;

    const x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
    
    const newColor = { ...color };
    switch (dragTarget) {
      case 'hue':
        newColor.hue = x;
        break;
      case 'saturation':
        newColor.saturation = x;
        break;
      case 'value':
        newColor.value = x;
        break;
    }

    onChange(newColor);
  }, [isDragging, dragTarget, disabled, color, onChange]);

  // 处理鼠标释放事件
  const handleMouseUp = useCallback(() => {
    setIsDragging(false);
    setDragTarget(null);
  }, []);

  // 添加全局事件监听器
  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      return () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };
    }
  }, [isDragging, handleMouseMove, handleMouseUp]);

  // 处理点击事件
  const handleClick = useCallback((
    e: React.MouseEvent,
    target: 'hue' | 'saturation' | 'value'
  ) => {
    if (disabled) return;

    const rect = e.currentTarget.getBoundingClientRect();
    const x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
    
    const newColor = { ...color };
    switch (target) {
      case 'hue':
        newColor.hue = x;
        break;
      case 'saturation':
        newColor.saturation = x;
        break;
      case 'value':
        newColor.value = x;
        break;
    }

    onChange(newColor);
  }, [disabled, color, onChange]);

  // 处理输入框变化
  const handleInputChange = useCallback((
    field: 'hue' | 'saturation' | 'value',
    value: string
  ) => {
    if (disabled) return;

    const numValue = parseFloat(value);
    if (isNaN(numValue)) return;

    const clampedValue = Math.max(0, Math.min(1, numValue));
    const newColor = { ...color, [field]: clampedValue };
    onChange(newColor);
  }, [disabled, color, onChange]);

  // 处理十六进制输入
  const handleHexChange = useCallback((hex: string) => {
    if (disabled) return;

    try {
      const newColor = ColorUtils.hexToHsv(hex);
      onChange(newColor);
    } catch (error) {
      // 忽略无效的十六进制值
    }
  }, [disabled, onChange]);

  // 生成色相条背景
  const hueBarBackground = 'linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)';

  // 生成饱和度条背景
  const saturationBarBackground = `linear-gradient(to right, 
    ${ColorUtils.hsvToHex({ hue: color.hue, saturation: 0, value: color.value })}, 
    ${ColorUtils.hsvToHex({ hue: color.hue, saturation: 1, value: color.value })})`;

  // 生成明度条背景
  const valueBarBackground = `linear-gradient(to right, 
    ${ColorUtils.hsvToHex({ hue: color.hue, saturation: color.saturation, value: 0 })}, 
    ${ColorUtils.hsvToHex({ hue: color.hue, saturation: color.saturation, value: 1 })})`;

  const currentHex = ColorUtils.hsvToHex(color);

  return (
    <div className={`color-picker ${disabled ? 'disabled' : ''}`}>
      {/* 颜色预览 */}
      <div className="color-preview-section">
        <div 
          className="color-preview"
          style={{ backgroundColor: currentHex }}
          title={`当前颜色: ${currentHex}`}
        />
        <div className="color-info">
          <input
            type="text"
            value={currentHex}
            onChange={(e) => handleHexChange(e.target.value)}
            disabled={disabled}
            className="hex-input"
            placeholder="#FFFFFF"
            maxLength={7}
          />
        </div>
      </div>

      {/* 色相滑块 */}
      <div className="slider-section">
        <label className="slider-label">色相 (H)</label>
        <div 
          ref={hueRef}
          className="color-slider hue-slider"
          style={{ background: hueBarBackground }}
          onMouseDown={() => handleMouseDown('hue')}
          onClick={(e) => handleClick(e, 'hue')}
        >
          <div 
            className="slider-thumb"
            style={{ left: `${color.hue * 100}%` }}
          />
        </div>
        <input
          type="number"
          value={color.hue.toFixed(3)}
          onChange={(e) => handleInputChange('hue', e.target.value)}
          disabled={disabled}
          className="value-input"
          min="0"
          max="1"
          step="0.001"
        />
      </div>

      {/* 饱和度滑块 */}
      <div className="slider-section">
        <label className="slider-label">饱和度 (S)</label>
        <div 
          ref={saturationRef}
          className="color-slider saturation-slider"
          style={{ background: saturationBarBackground }}
          onMouseDown={() => handleMouseDown('saturation')}
          onClick={(e) => handleClick(e, 'saturation')}
        >
          <div 
            className="slider-thumb"
            style={{ left: `${color.saturation * 100}%` }}
          />
        </div>
        <input
          type="number"
          value={color.saturation.toFixed(3)}
          onChange={(e) => handleInputChange('saturation', e.target.value)}
          disabled={disabled}
          className="value-input"
          min="0"
          max="1"
          step="0.001"
        />
      </div>

      {/* 明度滑块 */}
      <div className="slider-section">
        <label className="slider-label">明度 (V)</label>
        <div 
          ref={valueRef}
          className="color-slider value-slider"
          style={{ background: valueBarBackground }}
          onMouseDown={() => handleMouseDown('value')}
          onClick={(e) => handleClick(e, 'value')}
        >
          <div 
            className="slider-thumb"
            style={{ left: `${color.value * 100}%` }}
          />
        </div>
        <input
          type="number"
          value={color.value.toFixed(3)}
          onChange={(e) => handleInputChange('value', e.target.value)}
          disabled={disabled}
          className="value-input"
          min="0"
          max="1"
          step="0.001"
        />
      </div>

      {/* 预设颜色 */}
      <div className="preset-colors">
        <div className="preset-colors-label">常用颜色</div>
        <div className="preset-colors-grid">
          {PRESET_COLORS.map((presetColor, index) => (
            <button
              key={index}
              className="preset-color-button"
              style={{ backgroundColor: ColorUtils.hsvToHex(presetColor) }}
              onClick={() => !disabled && onChange(presetColor)}
              disabled={disabled}
              title={`预设颜色 ${index + 1}`}
            />
          ))}
        </div>
      </div>

      <style>{`
        .color-picker {
          padding: 16px;
          border: 1px solid #e5e7eb;
          border-radius: 8px;
          background: white;
          min-width: 280px;
        }

        .color-picker.disabled {
          opacity: 0.6;
          pointer-events: none;
        }

        .color-preview-section {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 16px;
        }

        .color-preview {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          border: 2px solid #e5e7eb;
          cursor: pointer;
        }

        .hex-input {
          padding: 8px 12px;
          border: 1px solid #d1d5db;
          border-radius: 6px;
          font-family: monospace;
          font-size: 14px;
          width: 100px;
        }

        .slider-section {
          margin-bottom: 12px;
        }

        .slider-label {
          display: block;
          font-size: 12px;
          font-weight: 500;
          color: #374151;
          margin-bottom: 4px;
        }

        .color-slider {
          position: relative;
          height: 20px;
          border-radius: 10px;
          cursor: pointer;
          margin-bottom: 4px;
          border: 1px solid #e5e7eb;
        }

        .slider-thumb {
          position: absolute;
          top: -2px;
          width: 16px;
          height: 24px;
          background: white;
          border: 2px solid #374151;
          border-radius: 3px;
          transform: translateX(-50%);
          cursor: grab;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .slider-thumb:active {
          cursor: grabbing;
        }

        .value-input {
          width: 80px;
          padding: 4px 8px;
          border: 1px solid #d1d5db;
          border-radius: 4px;
          font-size: 12px;
          text-align: center;
        }

        .preset-colors {
          margin-top: 16px;
          padding-top: 16px;
          border-top: 1px solid #e5e7eb;
        }

        .preset-colors-label {
          font-size: 12px;
          font-weight: 500;
          color: #374151;
          margin-bottom: 8px;
        }

        .preset-colors-grid {
          display: grid;
          grid-template-columns: repeat(8, 1fr);
          gap: 4px;
        }

        .preset-color-button {
          width: 24px;
          height: 24px;
          border: 1px solid #e5e7eb;
          border-radius: 4px;
          cursor: pointer;
          transition: transform 0.1s;
        }

        .preset-color-button:hover {
          transform: scale(1.1);
        }

        .preset-color-button:disabled {
          cursor: not-allowed;
          transform: none;
        }
      `}</style>
    </div>
  );
};

// 预设颜色
const PRESET_COLORS: ColorHSV[] = [
  { hue: 0, saturation: 1, value: 1 },     // 红色
  { hue: 0.083, saturation: 1, value: 1 }, // 橙色
  { hue: 0.167, saturation: 1, value: 1 }, // 黄色
  { hue: 0.333, saturation: 1, value: 1 }, // 绿色
  { hue: 0.5, saturation: 1, value: 1 },   // 青色
  { hue: 0.667, saturation: 1, value: 1 }, // 蓝色
  { hue: 0.833, saturation: 1, value: 1 }, // 紫色
  { hue: 0.917, saturation: 1, value: 1 }, // 粉色
  { hue: 0, saturation: 0, value: 0 },     // 黑色
  { hue: 0, saturation: 0, value: 0.2 },   // 深灰
  { hue: 0, saturation: 0, value: 0.5 },   // 中灰
  { hue: 0, saturation: 0, value: 0.8 },   // 浅灰
  { hue: 0, saturation: 0, value: 1 },     // 白色
  { hue: 0.083, saturation: 0.8, value: 0.6 }, // 棕色
  { hue: 0.167, saturation: 0.6, value: 0.9 }, // 米色
  { hue: 0.5, saturation: 0.3, value: 0.7 },   // 灰蓝
];

export default ColorPicker;
