import React, { useCallback, useState } from 'react';
import { open } from '@tauri-apps/plugin-dialog';
import { ImageUploaderProps, SUPPORTED_IMAGE_FORMATS } from '../../types/outfitSearch';
import { Upload, Image as ImageIcon, X, Sparkles, AlertCircle } from 'lucide-react';
import { convertFileSrc } from '@tauri-apps/api/core';
/**
 * 图像上传和分析组件
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const ImageUploader: React.FC<ImageUploaderProps> = ({
  onImageSelect,
  onAnalyzeImage,
  isAnalyzing,
  selectedImage,
  analysisError,
}) => {
  const [dragOver, setDragOver] = useState(false);
  const [error, setError] = useState<string | null>(null);
  // const fileInputRef = useRef<HTMLInputElement>(null);

  // 处理文件选择
  const handleFileSelect = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [
          {
            name: '图像文件',
            extensions: SUPPORTED_IMAGE_FORMATS,
          },
        ],
      });

      if (selected && typeof selected === 'string') {
        setError(null);
        onImageSelect(selected);
      }
    } catch (error) {
      console.error('Failed to select file:', error);
      setError('文件选择失败');
    }
  }, [onImageSelect]);

  // 处理拖拽进入
  const handleDragEnter = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOver(true);
  }, []);

  // 处理拖拽离开
  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOver(false);
  }, []);

  // 处理拖拽悬停
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);

  // 处理文件拖放
  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOver(false);

    const files = Array.from(e.dataTransfer.files);
    if (files.length === 0) return;

    const file = files[0];
    const extension = file.name.split('.').pop()?.toLowerCase();
    
    if (!extension || !SUPPORTED_IMAGE_FORMATS.includes(extension)) {
      setError(`不支持的文件格式。支持的格式：${SUPPORTED_IMAGE_FORMATS.join(', ')}`);
      return;
    }

    // 在实际应用中，这里需要将文件保存到本地并获取路径
    // 暂时使用文件名作为路径
    setError(null);
    onImageSelect(file.name);
  }, [onImageSelect]);

  // 执行图像分析
  const handleAnalyze = useCallback(() => {
    if (!selectedImage) return;

    setError(null);
    onAnalyzeImage(selectedImage);
  }, [selectedImage, onAnalyzeImage]);

  // 清除选择的图像
  const handleClearImage = useCallback(() => {
    onImageSelect(null);
    setError(null);
  }, [onImageSelect]);

  return (
    <div className="card p-6 animate-fade-in">
      <div className="flex items-center gap-3 mb-6">
        <div className="icon-container purple w-8 h-8">
          <ImageIcon className="w-4 h-4" />
        </div>
        <div>
          <h3 className="text-heading-4 text-high-emphasis">图像分析</h3>
          <p className="text-sm text-medium-emphasis">
            上传服装图片进行AI分析，提取颜色、风格和类别信息
          </p>
        </div>
      </div>

      {!selectedImage ? (
        <div
          className={`relative border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all duration-300 ${
            dragOver
              ? 'border-primary-500 bg-primary-50 scale-105'
              : 'border-gray-300 hover:border-primary-400 hover:bg-gray-50'
          }`}
          onDragEnter={handleDragEnter}
          onDragLeave={handleDragLeave}
          onDragOver={handleDragOver}
          onDrop={handleDrop}
          onClick={handleFileSelect}
        >
          <div className="space-y-4">
            <div className={`mx-auto w-16 h-16 rounded-full flex items-center justify-center transition-all duration-300 ${
              dragOver ? 'bg-primary-100 text-primary-600' : 'bg-gray-100 text-gray-400'
            }`}>
              <Upload className="w-8 h-8" />
            </div>
            <div>
              <p className="text-lg font-medium text-gray-900 mb-2">
                点击选择图片或拖拽图片到此处
              </p>
              <p className="text-sm text-gray-500">
                支持格式：{SUPPORTED_IMAGE_FORMATS.join(', ')}
              </p>
            </div>
          </div>

          {dragOver && (
            <div className="absolute inset-0 bg-primary-500 bg-opacity-10 rounded-xl animate-pulse" />
          )}
        </div>
      ) : (
        <div className="space-y-6 animate-slide-in-up">
          <div className="relative group">
            <div className="relative overflow-hidden rounded-xl bg-gray-100">
              <img
                src={`${convertFileSrc(selectedImage)}`}
                alt="Selected outfit"
                className="w-full h-64 object-cover transition-transform duration-300 group-hover:scale-105"
                onError={() => setError('图片加载失败')}
              />
              <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all duration-300" />
              <button
                onClick={handleClearImage}
                className="absolute top-3 right-3 w-8 h-8 bg-white bg-opacity-90 hover:bg-opacity-100 rounded-full flex items-center justify-center text-gray-600 hover:text-red-500 transition-all duration-200 opacity-0 group-hover:opacity-100"
                disabled={isAnalyzing}
                title="移除图片"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          </div>

          <div className="space-y-4">
            <button
              onClick={handleAnalyze}
              disabled={isAnalyzing}
              className="btn btn-primary w-full hover-lift"
            >
              {isAnalyzing ? (
                <>
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  AI分析中...
                </>
              ) : (
                <>
                  <Sparkles className="w-4 h-4" />
                  开始AI分析
                </>
              )}
            </button>

            {/* 分析失败时显示重试按钮 */}
            {(analysisError && analysisError.includes('AI分析服务返回了不完整的数据')) && (
              <button
                onClick={handleAnalyze}
                disabled={isAnalyzing}
                className="btn btn-outline w-full hover-lift"
              >
                <Sparkles className="w-4 h-4" />
                重新分析
              </button>
            )}
          </div>
        </div>
      )}

      {error && (
        <div className="flex items-center gap-3 p-4 bg-red-50 border border-red-200 rounded-xl text-red-800 animate-shake">
          <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0" />
          <span className="text-sm font-medium">{error}</span>
        </div>
      )}
    </div>

  );
};

export default ImageUploader;
