import React, { useState, useCallback, useEffect } from 'react';
import { open } from '@tauri-apps/plugin-dialog';
import {
  Upload,
  Sparkles,
  X,
  AlertCircle,
  Image as ImageIcon,
  Wand2,
  Settings,
  CheckCircle,
  XCircle
} from 'lucide-react';
import { ModelPhoto, PhotoType } from '../types/model';
import { OutfitImageGenerationRequest } from '../types/outfitImage';
import { ComfyUISettings } from '../types/outfitPhotoGeneration';
import { getImageSrc } from '../utils/imagePathUtils';
import { OutfitPhotoGenerationService } from '../services/outfitPhotoGenerationService';

interface OutfitImageGeneratorProps {
  modelId: string;
  modelPhotos: ModelPhoto[];
  onGenerate: (request: OutfitImageGenerationRequest) => Promise<void>;
  onBatchGenerate?: (requests: OutfitImageGenerationRequest[]) => Promise<void>;
  onClose?: () => void; // 添加关闭回调
  isGenerating?: boolean;
  disabled?: boolean;
  enableBatchMode?: boolean; // 是否启用批量模式
}

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

/**
 * 穿搭图片生成组件
 * 支持选择模特形象图片、上传商品图片、设置生成参数
 */
export const OutfitImageGenerator: React.FC<OutfitImageGeneratorProps> = ({
  modelId,
  modelPhotos,
  onGenerate,
  onBatchGenerate,
  onClose,
  isGenerating = false,
  disabled = false,
  enableBatchMode = true
}) => {
  const [selectedModelImageId, setSelectedModelImageId] = useState<string>('');
  const [productImages, setProductImages] = useState<string[]>([]);
  const [generationPrompt, setGenerationPrompt] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [dragOver, setDragOver] = useState(false);

  // ComfyUI 设置相关状态
  const [showSettings, setShowSettings] = useState(false);
  const [comfyUISettings, setComfyUISettings] = useState<ComfyUISettings | null>(null);
  const [connectionStatus, setConnectionStatus] = useState<'unknown' | 'connected' | 'failed'>('unknown');
  const [loadingSettings, setLoadingSettings] = useState(false);

  // 获取个人形象照片（用于穿搭生成）
  const portraitPhotos = modelPhotos.filter(photo => photo.photo_type === PhotoType.Portrait);

  // 加载 ComfyUI 设置
  const loadComfyUISettings = useCallback(async () => {
    try {
      setLoadingSettings(true);
      const settings = await OutfitPhotoGenerationService.getComfyUISettings();
      setComfyUISettings(settings);

      // 如果启用了 ComfyUI，测试连接
      if (settings.enabled) {
        try {
          const connected = await OutfitPhotoGenerationService.testComfyUIConnection();
          setConnectionStatus(connected ? 'connected' : 'failed');
        } catch (err) {
          setConnectionStatus('failed');
        }
      } else {
        setConnectionStatus('unknown');
      }
    } catch (err) {
      console.error('加载 ComfyUI 设置失败:', err);
      setConnectionStatus('failed');
    } finally {
      setLoadingSettings(false);
    }
  }, []);

  // 初始加载设置
  useEffect(() => {
    loadComfyUISettings();
  }, [loadComfyUISettings]);

  // 更新 ComfyUI 设置
  const handleSettingsUpdate = useCallback(async (newSettings: ComfyUISettings) => {
    try {
      await OutfitPhotoGenerationService.updateComfyUISettings(newSettings);
      setComfyUISettings(newSettings);

      // 重新测试连接
      if (newSettings.enabled) {
        try {
          const connected = await OutfitPhotoGenerationService.testComfyUIConnection();
          setConnectionStatus(connected ? 'connected' : 'failed');
        } catch (err) {
          setConnectionStatus('failed');
        }
      } else {
        setConnectionStatus('unknown');
      }
    } catch (err) {
      console.error('更新 ComfyUI 设置失败:', err);
      setError(`更新设置失败: ${err}`);
    }
  }, []);

  // 处理商品图片选择
  const handleProductImageSelect = useCallback(async () => {
    if (disabled || isGenerating) return;

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

      if (selected && Array.isArray(selected)) {
        if (selected.length > 10) {
          setError('最多只能选择 10 个商品图片');
          return;
        }
        
        setProductImages(prev => [...prev, ...selected]);
      }
    } catch (error) {
      console.error('Failed to select product images:', error);
      setError('商品图片选择失败');
    }
  }, [disabled, isGenerating]);

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

  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 || isGenerating) return;

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

    if (imagePaths.length > 0) {
      setError(null);
      setProductImages(prev => [...prev, ...imagePaths]);
    } else {
      setError('请选择有效的图片文件');
    }
  }, [disabled, isGenerating]);

  // 移除商品图片
  const removeProductImage = useCallback((index: number) => {
    setProductImages(prev => prev.filter((_, i) => i !== index));
  }, []);



  // 处理生成请求
  const handleGenerate = useCallback(async () => {
    if (!selectedModelImageId) {
      setError('请选择模特形象图片');
      return;
    }

    if (productImages.length === 0) {
      setError('请至少上传一张商品图片');
      return;
    }

    // 检查 ComfyUI 状态
    if (!comfyUISettings?.enabled) {
      setError('请先启用 ComfyUI 功能');
      setShowSettings(true);
      return;
    }

    if (!comfyUISettings?.workflow_directory) {
      setError('请先选择 ComfyUI 工作流文件');
      setShowSettings(true);
      return;
    }

    if (connectionStatus === 'failed') {
      setError('ComfyUI 连接失败，请检查设置');
      setShowSettings(true);
      return;
    }

    try {
      setError(null);

      if (enableBatchMode && onBatchGenerate && productImages.length > 1) {
        // 批量模式：为每个商品图片创建独立的生成请求
        const requests: OutfitImageGenerationRequest[] = productImages.map((productImagePath, index) => ({
          model_id: modelId,
          model_image_id: selectedModelImageId,
          product_image_paths: [productImagePath], // 每个任务只包含一个商品图片
          generation_prompt: generationPrompt || undefined,
          style_preferences: undefined,
          product_index: index // 添加商品编号
        }));

        // 使用批量生成方法（并发执行）
        await onBatchGenerate(requests);
      } else {
        // 单个模式或回退模式：为每个商品图片创建独立的生成任务
        const generatePromises = productImages.map(async (productImagePath, index) => {
          const request: OutfitImageGenerationRequest = {
            model_id: modelId,
            model_image_id: selectedModelImageId,
            product_image_paths: [productImagePath], // 每个任务只包含一个商品图片
            generation_prompt: generationPrompt || undefined,
            style_preferences: undefined,
            product_index: index // 添加商品编号
          };

          return await onGenerate(request);
        });

        // 等待所有任务创建完成
        await Promise.all(generatePromises);
      }

      // 生成成功后清空表单
      setSelectedModelImageId('');
      setProductImages([]);
      setGenerationPrompt('');

      // 异步模式：任务已提交，弹框会自动关闭
      // 不需要手动关闭，让父组件处理
    } catch (error) {
      console.error('生成穿搭图片失败:', error);
      setError(`生成穿搭图片失败: ${error}`);
    }
  }, [modelId, selectedModelImageId, productImages, generationPrompt, onGenerate, onClose, comfyUISettings, connectionStatus]);

  const canGenerate = selectedModelImageId &&
                     productImages.length > 0 &&
                     !isGenerating &&
                     !disabled &&
                     comfyUISettings?.enabled &&
                     connectionStatus === 'connected' &&
                     comfyUISettings?.workflow_directory;

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 space-y-6">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center">
          <div className="w-2 h-8 bg-gradient-to-b from-purple-500 to-purple-600 rounded-full mr-4"></div>
          <h2 className="text-xl font-bold text-gray-900">穿搭图片生成</h2>
          <Sparkles className="w-6 h-6 text-purple-500 ml-2" />
        </div>

        {/* ComfyUI 状态和设置 */}
        <div className="flex items-center space-x-3">
          {/* 连接状态指示器 */}
          {loadingSettings ? (
            <div className="flex items-center text-sm text-gray-500">
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-400 mr-2"></div>
              检查中...
            </div>
          ) : comfyUISettings?.enabled ? (
            <div className="flex items-center text-sm">
              {connectionStatus === 'connected' ? (
                <>
                  <CheckCircle className="w-4 h-4 text-green-500 mr-1" />
                  <span className="text-green-600">ComfyUI 已连接</span>
                </>
              ) : connectionStatus === 'failed' ? (
                <>
                  <XCircle className="w-4 h-4 text-red-500 mr-1" />
                  <span className="text-red-600">ComfyUI 连接失败</span>
                </>
              ) : (
                <>
                  <AlertCircle className="w-4 h-4 text-yellow-500 mr-1" />
                  <span className="text-yellow-600">状态未知</span>
                </>
              )}
            </div>
          ) : (
            <div className="flex items-center text-sm text-gray-500">
              <XCircle className="w-4 h-4 mr-1" />
              ComfyUI 未启用
            </div>
          )}

          {/* 设置按钮 */}
          <button
            onClick={() => setShowSettings(!showSettings)}
            className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
            title="ComfyUI 设置"
          >
            <Settings className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* ComfyUI 设置面板 */}
      {showSettings && (
        <div className="bg-gray-50 border border-gray-200 rounded-xl p-4 space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold text-gray-900">ComfyUI 设置</h3>
            <button
              onClick={() => setShowSettings(false)}
              className="text-gray-400 hover:text-gray-600"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {comfyUISettings && (
            <div className="space-y-4">
              {/* 启用开关 */}
              <div className="flex items-center justify-between">
                <div>
                  <label className="text-sm font-medium text-gray-700">启用 ComfyUI</label>
                  <p className="text-xs text-gray-500">开启穿搭照片生成功能</p>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={comfyUISettings.enabled}
                    onChange={(e) => handleSettingsUpdate({
                      ...comfyUISettings,
                      enabled: e.target.checked
                    })}
                    className="sr-only peer"
                  />
                  <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                </label>
              </div>

              {/* 服务器设置 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    服务器地址
                  </label>
                  <input
                    type="text"
                    value={comfyUISettings.server_address}
                    onChange={(e) => handleSettingsUpdate({
                      ...comfyUISettings,
                      server_address: e.target.value
                    })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                    placeholder="127.0.0.1"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    端口号
                  </label>
                  <input
                    type="number"
                    value={comfyUISettings.server_port}
                    onChange={(e) => handleSettingsUpdate({
                      ...comfyUISettings,
                      server_port: parseInt(e.target.value) || 8188
                    })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                    placeholder="8188"
                  />
                </div>
              </div>

              {/* 工作流文件设置 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  工作流文件
                </label>
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={comfyUISettings.workflow_directory || ''}
                    onChange={(e) => handleSettingsUpdate({
                      ...comfyUISettings,
                      workflow_directory: e.target.value || undefined
                    })}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                    placeholder="选择工作流JSON文件..."
                    readOnly
                  />
                  <button
                    onClick={async () => {
                      try {
                        const selected = await open({
                          filters: [{
                            name: 'JSON Files',
                            extensions: ['json']
                          }],
                          multiple: false
                        });
                        if (selected) {
                          handleSettingsUpdate({
                            ...comfyUISettings,
                            workflow_directory: selected as string
                          });
                        }
                      } catch (err) {
                        console.error('选择文件失败:', err);
                      }
                    }}
                    className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                  >
                    选择文件
                  </button>
                </div>
                <p className="text-xs text-gray-500 mt-1">
                  选择ComfyUI工作流JSON文件（如：换装-MidJourney.json）
                </p>
              </div>

              {/* 测试连接按钮 */}
              <div className="flex justify-end">
                <button
                  onClick={loadComfyUISettings}
                  disabled={!comfyUISettings.enabled || loadingSettings}
                  className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
                >
                  {loadingSettings ? '测试中...' : '测试连接'}
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {/* 选择模特形象图片 */}
      <div className="space-y-4">
        <h3 className="text-lg font-semibold text-gray-900 flex items-center">
          <ImageIcon className="w-5 h-5 mr-2" />
          选择模特形象图片
        </h3>
        
        {portraitPhotos.length === 0 ? (
          <div className="text-center py-8 bg-gray-50 rounded-xl">
            <ImageIcon className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <p className="text-gray-500">暂无个人形象照片，请先上传形象照片</p>
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
            {portraitPhotos.map((photo) => (
              <div
                key={photo.id}
                className={`relative aspect-square rounded-xl overflow-hidden border-2 cursor-pointer transition-all duration-200 ${
                  selectedModelImageId === photo.id
                    ? 'border-purple-500 ring-2 ring-purple-200 scale-105'
                    : 'border-gray-200 hover:border-purple-300 hover:scale-102'
                }`}
                onClick={() => setSelectedModelImageId(photo.id)}
              >
                <img
                  src={getImageSrc(photo.file_path)}
                  alt={photo.file_name}
                  className="w-full h-full object-cover"
                />
                {selectedModelImageId === photo.id && (
                  <div className="absolute inset-0 bg-purple-500 bg-opacity-20 flex items-center justify-center">
                    <div className="w-8 h-8 bg-purple-500 rounded-full flex items-center justify-center">
                      <Sparkles className="w-5 h-5 text-white" />
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 上传商品图片 */}
      <div className="space-y-4">
        <h3 className="text-lg font-semibold text-gray-900 flex items-center">
          <Upload className="w-5 h-5 mr-2" />
          上传商品图片
          <span className="text-sm text-gray-500 ml-2">({productImages.length}/10)</span>
          {enableBatchMode && productImages.length > 1 && (
            <span className="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full ml-2">
              批量模式
            </span>
          )}
        </h3>

        {/* 拖拽上传区域 */}
        <div
          className={`border-2 border-dashed rounded-xl p-6 text-center transition-all duration-200 ${
            dragOver
              ? 'border-purple-400 bg-purple-50'
              : disabled || isGenerating
              ? 'border-gray-200 bg-gray-50'
              : 'border-gray-300 bg-white hover:border-purple-400 hover:bg-purple-50'
          } ${disabled || isGenerating ? 'cursor-not-allowed' : 'cursor-pointer'}`}
          onDragEnter={handleDragEnter}
          onDragLeave={handleDragLeave}
          onDragOver={handleDragOver}
          onDrop={handleDrop}
          onClick={handleProductImageSelect}
        >
          <div className="flex flex-col items-center">
            <div className={`p-3 rounded-full mb-4 ${
              dragOver ? 'bg-purple-100' : 'bg-gray-100'
            }`}>
              <Upload className={`w-8 h-8 ${
                dragOver ? 'text-purple-600' : 'text-gray-400'
              }`} />
            </div>
            
            <h4 className="text-lg font-medium text-gray-900 mb-2">
              {dragOver ? '释放以上传商品图片' : '上传商品图片'}
            </h4>
            
            <p className="text-sm text-gray-500 mb-4">
              拖拽图片到此处，或点击选择文件
            </p>
            
            <div className="flex items-center space-x-4 text-xs text-gray-400">
              <span>支持格式：{SUPPORTED_IMAGE_FORMATS.join(', ').toUpperCase()}</span>
              <span>•</span>
              <span>最多 10 个文件</span>
            </div>
          </div>
        </div>

        {/* 已上传的商品图片 */}
        {productImages.length > 0 && (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-4">
            {productImages.map((imagePath, index) => (
              <div key={index} className="relative group">
                <div className="aspect-square rounded-lg overflow-hidden border border-gray-200">
                  <img
                    src={getImageSrc(imagePath)}
                    alt={`商品图片 ${index + 1}`}
                    className="w-full h-full object-cover"
                  />
                </div>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    removeProductImage(index);
                  }}
                  className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center hover:bg-red-600"
                  title="删除图片"
                >
                  <X className="w-3 h-3" />
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 生成参数设置 */}
      <div className="space-y-4">
        <h3 className="text-lg font-semibold text-gray-900 flex items-center">
          <Settings className="w-5 h-5 mr-2" />
          生成参数设置
        </h3>

        {/* 生成提示词 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            生成提示词（可选）
          </label>
          <textarea
            value={generationPrompt}
            onChange={(e) => setGenerationPrompt(e.target.value)}
            placeholder="描述您希望生成的穿搭风格，例如：时尚、休闲、商务、运动等..."
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent resize-none"
            rows={3}
            disabled={disabled || isGenerating}
          />
        </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 className="flex justify-end pt-4 border-t border-gray-200">
        <button
          onClick={handleGenerate}
          disabled={!canGenerate}
          className={`flex items-center px-6 py-3 rounded-lg font-medium transition-all duration-200 ${
            canGenerate
              ? 'bg-purple-600 text-white hover:bg-purple-700 hover:scale-105 shadow-lg hover:shadow-xl'
              : 'bg-gray-300 text-gray-500 cursor-not-allowed'
          }`}
        >
          {isGenerating ? (
            <>
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
              {enableBatchMode && productImages.length > 1 ?
                `批量生成中... (${productImages.length}个任务)` :
                '生成中...'
              }
            </>
          ) : (
            <>
              <Wand2 className="w-5 h-5 mr-2" />
              {enableBatchMode && productImages.length > 1 ?
                `批量生成穿搭图片 (${productImages.length}个任务)` :
                '生成穿搭图片'
              }
            </>
          )}
        </button>
      </div>

      {/* 使用说明 */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <div className="flex items-start">
          <Sparkles className="w-5 h-5 text-blue-500 mr-2 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-blue-700">
            <p className="font-medium mb-1">使用说明：</p>
            <ul className="space-y-1 text-xs">
              <li>• 选择一张模特的个人形象照片作为基础</li>
              <li>• 上传要搭配的商品图片（服装、配饰等）</li>
              <li>• 可选择添加生成提示词来指导AI生成</li>
              <li>• 点击生成按钮，AI将为每个商品创建独立的生成任务</li>
              <li>• 多个商品将同时生成，每个商品对应一个任务记录</li>
              <li>• 可在生成记录中查看每个任务的进度和结果</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
};

export default OutfitImageGenerator;
