import React, { useCallback, useState } from 'react';
import { open } from '@tauri-apps/plugin-dialog';
import {
  Upload,
  X,
  AlertCircle
} from 'lucide-react';
import { PhotoType } from '../types/model';

interface ModelImageUploaderProps {
  onImagesSelect: (imagePaths: string[], photoType: PhotoType) => void;
  isUploading?: boolean;
  disabled?: boolean;
  maxFiles?: number;
  acceptedFormats?: string[];
}

const SUPPORTED_IMAGE_FORMATS = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'];

/**
 * 模特图片上传组件
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const ModelImageUploader: React.FC<ModelImageUploaderProps> = ({
  onImagesSelect,
  isUploading = false,
  disabled = false,
  maxFiles = 10,
  acceptedFormats = SUPPORTED_IMAGE_FORMATS,
}) => {
  const [dragOver, setDragOver] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 处理文件选择
  const handleFileSelect = useCallback(async () => {
    if (disabled || isUploading) return;

    try {
      setError(null);
      
      const selected = await open({
        multiple: true,
        filters: [
          {
            name: '图像文件',
            extensions: acceptedFormats,
          },
        ],
      });

      if (selected && Array.isArray(selected)) {
        if (selected.length > maxFiles) {
          setError(`最多只能选择 ${maxFiles} 个文件`);
          return;
        }
        
        onImagesSelect(selected, PhotoType.Portrait);
      }
    } catch (error) {
      console.error('Failed to select files:', error);
      setError('文件选择失败');
    }
  }, [onImagesSelect, disabled, isUploading, maxFiles, acceptedFormats]);

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

  // 处理拖拽离开
  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);

    if (disabled || isUploading) return;

    const files = Array.from(e.dataTransfer.files);
    const imagePaths = files
      .filter(file => {
        const extension = file.name.split('.').pop()?.toLowerCase();
        return extension && acceptedFormats.includes(extension);
      })
      .slice(0, maxFiles)
      .map(file => (file as any).path || file.name);

    if (imagePaths.length > 0) {
      setError(null);
      onImagesSelect(imagePaths, PhotoType.Portrait);
    } else {
      setError('请选择有效的图片文件');
    }
  }, [onImagesSelect, disabled, isUploading, maxFiles, acceptedFormats]);

  return (
    <div className="space-y-4">

      {/* 上传区域 */}
      <div
        className={`relative border-2 border-dashed rounded-xl p-8 text-center transition-all duration-200 ${
          dragOver
            ? 'border-blue-400 bg-blue-50'
            : disabled || isUploading
            ? 'border-gray-200 bg-gray-50'
            : 'border-gray-300 bg-white hover:border-blue-400 hover:bg-blue-50'
        } ${disabled || isUploading ? 'cursor-not-allowed' : 'cursor-pointer'}`}
        onDragEnter={handleDragEnter}
        onDragLeave={handleDragLeave}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
        onClick={handleFileSelect}
      >
        {isUploading ? (
          <div className="flex flex-col items-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
            <p className="text-blue-600 font-medium">正在上传图片...</p>
            <p className="text-sm text-gray-500 mt-1">请稍候</p>
          </div>
        ) : (
          <div className="flex flex-col items-center">
            <div className={`p-3 rounded-full mb-4 ${
              dragOver ? 'bg-blue-100' : 'bg-gray-100'
            }`}>
              <Upload className={`w-8 h-8 ${
                dragOver ? 'text-blue-600' : 'text-gray-400'
              }`} />
            </div>
            
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              {dragOver ? '释放以上传图片' : '上传模特照片'}
            </h3>
            
            <p className="text-sm text-gray-500 mb-4">
              拖拽图片到此处，或点击选择文件
            </p>
            
            <div className="flex items-center space-x-4 text-xs text-gray-400">
              <span>支持格式：{acceptedFormats.join(', ').toUpperCase()}</span>
              <span>•</span>
              <span>最多 {maxFiles} 个文件</span>
            </div>
          </div>
        )}
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="flex items-center p-3 bg-red-50 border border-red-200 rounded-lg">
          <AlertCircle className="w-5 h-5 text-red-500 mr-2 flex-shrink-0" />
          <span className="text-sm text-red-700">{error}</span>
          <button
            onClick={() => setError(null)}
            className="ml-auto text-red-500 hover:text-red-700"
          >
            <X className="w-4 h-4" />
          </button>
        </div>
      )}


    </div>
  );
};

export default ModelImageUploader;
