/**
 * 穿搭照片生成器组件
 * 基于 ComfyUI 工作流的穿搭照片生成功能
 */

import React, { useState, useCallback } from 'react';
import { open } from '@tauri-apps/plugin-dialog';
import {
  Upload,
  Sparkles,
  X,
  AlertCircle,
  Image as ImageIcon,
  Wand2,
  Settings,
  RotateCcw,
  Download,
  Eye
} from 'lucide-react';
import { ModelPhoto, PhotoType } from '../../types/model';
import type {
  OutfitPhotoGenerationRequest,
  OutfitPhotoGenerationResponse,
  WorkflowProgress,
  WorkflowConfig
} from '../../types/outfitPhotoGeneration';
import { GenerationStatus } from '../../types/outfitPhotoGeneration';
import { OutfitPhotoGenerationService } from '../../services/outfitPhotoGenerationService';
import { getImageSrc } from '../../utils/imagePathUtils';
import { LoadingSpinner } from '../LoadingSpinner';
import { Modal } from '../Modal';

interface OutfitPhotoGeneratorProps {
  projectId: string;
  modelId: string;
  modelPhotos: ModelPhoto[];
  onGenerationComplete?: (response: OutfitPhotoGenerationResponse) => void;
  disabled?: boolean;
}

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

export const OutfitPhotoGenerator: React.FC<OutfitPhotoGeneratorProps> = ({
  projectId,
  modelId,
  modelPhotos,
  onGenerationComplete,
  disabled = false
}) => {
  // 基础状态
  const [selectedModelImageId, setSelectedModelImageId] = useState<string>('');
  const [productImages, setProductImages] = useState<string[]>([]);
  const [prompt, setPrompt] = useState('');
  const [negativePrompt, setNegativePrompt] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [dragOver, setDragOver] = useState(false);

  // 生成状态
  const [isGenerating, setIsGenerating] = useState(false);
  const [generationProgress, setGenerationProgress] = useState<WorkflowProgress | null>(null);
  const [generationResult, setGenerationResult] = useState<OutfitPhotoGenerationResponse | null>(null);

  // 工作流配置
  const [workflowConfig, setWorkflowConfig] = useState<WorkflowConfig>({
    workflow_file_path: '',
    steps: 20,
    cfg_scale: 7.0,
    seed: -1,
    sampler: 'euler',
    scheduler: 'normal',
    denoise: 1.0
  });

  // 高级设置
  const [showAdvancedSettings, setShowAdvancedSettings] = useState(false);
  const [showResultModal, setShowResultModal] = useState(false);

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

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

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

      if (selected && Array.isArray(selected)) {
        setProductImages(prev => [...prev, ...selected]);
        setError(null);
      }
    } catch (err) {
      console.error('选择商品图片失败:', err);
      setError('选择商品图片失败');
    }
  }, [disabled, isGenerating]);

  // 处理拖拽上传
  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(false);

    if (disabled || isGenerating) return;

    const files = Array.from(e.dataTransfer.files);
    const imageFiles = files.filter(file => {
      const extension = file.name.split('.').pop()?.toLowerCase();
      return extension && SUPPORTED_IMAGE_FORMATS.includes(extension);
    });

    if (imageFiles.length > 0) {
      const imagePaths = imageFiles.map(file => {
        // In Tauri, files from drag & drop should have a path property
        return (file as any).path || URL.createObjectURL(file);
      });
      setProductImages(prev => [...prev, ...imagePaths]);
      setError(null);
    }
  }, [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;
    }

    if (!prompt.trim()) {
      setError('请输入生成提示词');
      return;
    }

    try {
      setError(null);
      setIsGenerating(true);
      setGenerationProgress(null);
      setGenerationResult(null);

      // 构建生成请求
      const request: OutfitPhotoGenerationRequest = {
        project_id: projectId,
        model_id: modelId,
        product_image_path: productImages[0], // 暂时只支持单张商品图片
        prompt: prompt.trim(),
        negative_prompt: negativePrompt.trim() || undefined,
        workflow_config: workflowConfig.workflow_file_path ? workflowConfig : undefined
      };

      // 创建生成任务
      const taskId = await OutfitPhotoGenerationService.createGenerationTask(request);

      // 执行生成任务
      const response = await OutfitPhotoGenerationService.executeGeneration(
        taskId,
        (progress) => {
          setGenerationProgress(progress);
        }
      );

      setGenerationResult(response);
      
      if (response.status === GenerationStatus.Completed) {
        setShowResultModal(true);
        onGenerationComplete?.(response);
      } else if (response.status === GenerationStatus.Failed) {
        setError(response.error_message || '生成失败');
      }

    } catch (err) {
      console.error('生成穿搭照片失败:', err);
      setError(err instanceof Error ? err.message : '生成失败');
    } finally {
      setIsGenerating(false);
      setGenerationProgress(null);
    }
  }, [
    selectedModelImageId,
    productImages,
    prompt,
    negativePrompt,
    workflowConfig,
    projectId,
    modelId,
    onGenerationComplete
  ]);

  // 重试生成
  const handleRetry = useCallback(async () => {
    if (!generationResult) return;

    try {
      setError(null);
      setIsGenerating(true);
      
      const response = await OutfitPhotoGenerationService.retryGeneration(generationResult.id);
      setGenerationResult(response);
      
      if (response.status === GenerationStatus.Completed) {
        setShowResultModal(true);
        onGenerationComplete?.(response);
      } else if (response.status === GenerationStatus.Failed) {
        setError(response.error_message || '重试失败');
      }
    } catch (err) {
      console.error('重试生成失败:', err);
      setError(err instanceof Error ? err.message : '重试失败');
    } finally {
      setIsGenerating(false);
    }
  }, [generationResult, onGenerationComplete]);

  // 清空表单
  const handleClear = useCallback(() => {
    setSelectedModelImageId('');
    setProductImages([]);
    setPrompt('');
    setNegativePrompt('');
    setError(null);
    setGenerationResult(null);
    setGenerationProgress(null);
  }, []);

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
          <Sparkles className="w-5 h-5 text-purple-500" />
          穿搭照片生成
        </h3>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowAdvancedSettings(!showAdvancedSettings)}
            className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
            title="高级设置"
          >
            <Settings className="w-4 h-4" />
          </button>
          <button
            onClick={handleClear}
            disabled={isGenerating}
            className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50"
            title="清空表单"
          >
            <RotateCcw className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2 text-red-700">
          <AlertCircle className="w-4 h-4 flex-shrink-0" />
          <span className="text-sm">{error}</span>
        </div>
      )}

      {/* 生成进度 */}
      {isGenerating && generationProgress && (
        <div className="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-blue-900">{generationProgress.stage}</span>
            <span className="text-sm text-blue-700">{Math.round(generationProgress.progress)}%</span>
          </div>
          <div className="w-full bg-blue-200 rounded-full h-2">
            <div 
              className="bg-blue-600 h-2 rounded-full transition-all duration-300"
              style={{ width: `${generationProgress.progress}%` }}
            />
          </div>
          {generationProgress.message && (
            <p className="text-xs text-blue-600 mt-1">{generationProgress.message}</p>
          )}
        </div>
      )}

      <div className="space-y-6">
        {/* 模特形象选择 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            选择模特形象 <span className="text-red-500">*</span>
          </label>
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
            {portraitPhotos.map((photo) => (
              <div
                key={photo.id}
                className={`relative cursor-pointer rounded-lg overflow-hidden border-2 transition-all ${
                  selectedModelImageId === photo.id
                    ? 'border-purple-500 ring-2 ring-purple-200'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
                onClick={() => setSelectedModelImageId(photo.id)}
              >
                <div className="aspect-square">
                  <img
                    src={getImageSrc(photo.file_path)}
                    alt={photo.description || '模特形象'}
                    className="w-full h-full object-cover"
                  />
                </div>
                {selectedModelImageId === photo.id && (
                  <div className="absolute inset-0 bg-purple-500 bg-opacity-20 flex items-center justify-center">
                    <div className="w-6 h-6 bg-purple-500 rounded-full flex items-center justify-center">
                      <svg className="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
          {portraitPhotos.length === 0 && (
            <p className="text-sm text-gray-500 text-center py-8">
              暂无可用的模特形象图片，请先上传模特照片
            </p>
          )}
        </div>

        {/* 商品图片上传 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            上传商品图片 <span className="text-red-500">*</span>
          </label>
          <div
            className={`border-2 border-dashed rounded-lg p-6 text-center transition-colors ${
              dragOver
                ? 'border-purple-400 bg-purple-50'
                : 'border-gray-300 hover:border-gray-400'
            }`}
            onDrop={handleDrop}
            onDragOver={(e) => {
              e.preventDefault();
              setDragOver(true);
            }}
            onDragLeave={() => setDragOver(false)}
          >
            <Upload className="w-8 h-8 text-gray-400 mx-auto mb-2" />
            <p className="text-sm text-gray-600 mb-2">
              拖拽图片到此处，或
              <button
                onClick={handleProductImageSelect}
                disabled={disabled || isGenerating}
                className="text-purple-600 hover:text-purple-700 font-medium ml-1 disabled:opacity-50"
              >
                点击选择
              </button>
            </p>
            <p className="text-xs text-gray-500">
              支持 PNG、JPG、JPEG、GIF、BMP、WebP 格式
            </p>
          </div>

          {/* 已选择的商品图片 */}
          {productImages.length > 0 && (
            <div className="mt-3 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
              {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={() => removeProductImage(index)}
                    className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 提示词输入 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            生成提示词 <span className="text-red-500">*</span>
          </label>
          <textarea
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            disabled={disabled || isGenerating}
            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 disabled:opacity-50"
            rows={3}
          />
        </div>

        {/* 负面提示词 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            负面提示词（可选）
          </label>
          <textarea
            value={negativePrompt}
            onChange={(e) => setNegativePrompt(e.target.value)}
            disabled={disabled || isGenerating}
            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 disabled:opacity-50"
            rows={2}
          />
        </div>

        {/* 高级设置 */}
        {showAdvancedSettings && (
          <div className="p-4 bg-gray-50 rounded-lg border border-gray-200 space-y-4">
            <h4 className="text-sm font-medium text-gray-700 mb-3">高级设置</h4>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">生成步数</label>
                <input
                  type="number"
                  value={workflowConfig.steps || 20}
                  onChange={(e) => setWorkflowConfig(prev => ({ ...prev, steps: parseInt(e.target.value) || 20 }))}
                  min="1"
                  max="100"
                  className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-purple-500 focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">CFG 比例</label>
                <input
                  type="number"
                  value={workflowConfig.cfg_scale || 7.0}
                  onChange={(e) => setWorkflowConfig(prev => ({ ...prev, cfg_scale: parseFloat(e.target.value) || 7.0 }))}
                  min="1"
                  max="20"
                  step="0.1"
                  className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-purple-500 focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">种子值</label>
                <input
                  type="number"
                  value={workflowConfig.seed || -1}
                  onChange={(e) => setWorkflowConfig(prev => ({ ...prev, seed: parseInt(e.target.value) || -1 }))}
                  className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-purple-500 focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">去噪强度</label>
                <input
                  type="number"
                  value={workflowConfig.denoise || 1.0}
                  onChange={(e) => setWorkflowConfig(prev => ({ ...prev, denoise: parseFloat(e.target.value) || 1.0 }))}
                  min="0"
                  max="1"
                  step="0.1"
                  className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-purple-500 focus:border-transparent"
                />
              </div>
            </div>
          </div>
        )}

        {/* 生成按钮 */}
        <div className="flex items-center justify-between pt-4">
          <div className="flex items-center gap-2">
            {generationResult && generationResult.status === GenerationStatus.Failed && (
              <button
                onClick={handleRetry}
                disabled={isGenerating}
                className="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 disabled:opacity-50 flex items-center gap-2 transition-colors"
              >
                <RotateCcw className="w-4 h-4" />
                重试
              </button>
            )}
          </div>
          
          <button
            onClick={handleGenerate}
            disabled={disabled || isGenerating || !selectedModelImageId || productImages.length === 0 || !prompt.trim()}
            className="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 flex items-center gap-2 transition-colors"
          >
            {isGenerating ? (
              <>
                <LoadingSpinner size="small" />
                生成中...
              </>
            ) : (
              <>
                <Wand2 className="w-4 h-4" />
                开始生成
              </>
            )}
          </button>
        </div>
      </div>

      {/* 生成结果模态框 */}
      {showResultModal && generationResult && (
        <Modal
          isOpen={showResultModal}
          onClose={() => setShowResultModal(false)}
          title="生成结果"
          size="lg"
        >
          <div className="space-y-4">
            {generationResult.result_image_urls.length > 0 ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {generationResult.result_image_urls.map((url, index) => (
                  <div key={index} className="relative group">
                    <img
                      src={url}
                      alt={`生成结果 ${index + 1}`}
                      className="w-full rounded-lg"
                    />
                    <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all rounded-lg flex items-center justify-center opacity-0 group-hover:opacity-100">
                      <div className="flex gap-2">
                        <button
                          onClick={() => window.open(url, '_blank')}
                          className="p-2 bg-white text-gray-700 rounded-lg hover:bg-gray-100 transition-colors"
                          title="查看大图"
                        >
                          <Eye className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => {
                            const a = document.createElement('a');
                            a.href = url;
                            a.download = `outfit_${index + 1}.jpg`;
                            a.click();
                          }}
                          className="p-2 bg-white text-gray-700 rounded-lg hover:bg-gray-100 transition-colors"
                          title="下载图片"
                        >
                          <Download className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8">
                <ImageIcon className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                <p className="text-gray-500">暂无生成结果</p>
              </div>
            )}
            
            {generationResult.generation_time_ms && (
              <div className="text-sm text-gray-500 text-center">
                生成耗时: {(generationResult.generation_time_ms / 1000).toFixed(1)} 秒
              </div>
            )}
          </div>
        </Modal>
      )}
    </div>
  );
};
