
import React, { useState, useEffect, useMemo } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Progress } from '@/components/ui/progress';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import {
  User,
  Play,
  Loader2,
  CheckCircle,
  Wand2,
  Sparkles,
  Image as ImageIcon,
  FileText,
  Zap,
  Save,
  Upload,
  Plus,
  Settings,
  Palette,
  Camera,
  Shirt,
  ImageIcon as ImageIcon2
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { materialLibraryAPI } from '@/api/materials';
import { textTemplateAPI } from '@/api/textTemplates';
import { aiSwapAPI } from '@/api/ai_swap';
import { aiSwapBgAPI } from '@/api/ai_swap_bg';
import { aiSwapClothAPI } from '@/api/ai_swap_cloth';
import { aiSwapFaceAPI} from '@/api/ai_swap_face';
import { aiGenVideoAPI } from '@/api/ai_gen_video';
import { useAuth } from '@/contexts/AuthContext';

// 素材选择卡片组件（保留原有大小）
const MaterialCard = ({ item, isSelected, onSelect, type = 'image' }) => (
  <motion.div
    whileHover={{ scale: 1.02 }}
    className={`relative aspect-square bg-slate-100 rounded-lg overflow-hidden cursor-pointer transition-all ${
      isSelected ? 'ring-2 ring-blue-500 shadow-lg' : 'hover:ring-2 hover:ring-slate-300'
    }`}
    onClick={() => onSelect(item.id)}
  >
    {item.file_url ? (
      <img
        src={item.file_url}
        alt={item.original_filename}
        className="w-full h-full object-cover"
      />
    ) : (
      <div className="w-full h-full flex flex-col items-center justify-center text-slate-400">
        <ImageIcon className="w-8 h-8 mb-2" />
        <span className="text-xs">暂无图片</span>
      </div>
    )}
    {isSelected && (
      <div className="absolute top-2 right-2 w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">
        <CheckCircle className="w-4 h-4 text-white" />
      </div>
    )}
    <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-2">
      <p className="text-white text-xs font-medium truncate">
        {item.original_filename}
      </p>
    </div>
  </motion.div>
);

// 模板选择组件
const TemplateItem = ({ template, isSelected, onSelect, type }) => (
  <motion.div
    whileHover={{ scale: 1.01 }}
    className={`p-3 rounded-lg border cursor-pointer transition-all ${
      isSelected ? 'border-blue-500 bg-blue-50' : 'border-slate-200 hover:border-slate-300'
    }`}
    onClick={() => onSelect(template.id)}
  >
    <div className="flex items-center justify-between mb-2">
      <span className="text-sm font-medium">{template.name}</span>
      {isSelected && <CheckCircle className="w-4 h-4 text-blue-500" />}
    </div>
    <Badge variant="outline" className="text-xs">
      {template.tag || type}
    </Badge>
  </motion.div>
);

export default function AIGeneration() {
  const { user } = useAuth();
  
  // 状态管理
  const [originalImages, setOriginalImages] = useState([]);
  const [ipCharacters, setIpCharacters] = useState([]);
  const [clothingItems, setClothingItems] = useState([]);
  const [sceneTemplates, setSceneTemplates] = useState([]);
  const [copyTemplates, setCopyTemplates] = useState([]);

  const [selectedOriginalImages, setSelectedOriginalImages] = useState([]);
  const [selectedIpCharacters, setSelectedIpCharacters] = useState([]);
  const [selectedClothingItems, setSelectedClothingItems] = useState([]);
  const [selectedSceneTemplates, setSelectedSceneTemplates] = useState([]);
  const [selectedCopyTemplates, setSelectedCopyTemplates] = useState([]);

  const [taskName, setTaskName] = useState('');
  const [selectedTaskTypes, setSelectedTaskTypes] = useState([]);
  const [quantityPerGroup, setQuantityPerGroup] = useState(1);
  const [generationType, setGenerationType] = useState('image'); // 新增：生成类型选择（图片/视频）
  const [freePrompt, setFreePrompt] = useState(''); // 新增：自由提示
  const [isGenerating, setIsGenerating] = useState(false);
  const [generationProgress, setGenerationProgress] = useState(0);
  const [currentTask, setCurrentTask] = useState('');
  const [message, setMessage] = useState(null);
  const [loading, setLoading] = useState(false);
  const [currentTaskId, setCurrentTaskId] = useState(null); // 兼容保留，展示第一个任务ID
  const [currentTaskIds, setCurrentTaskIds] = useState([]); // 多任务ID
  const [taskStatus, setTaskStatus] = useState(null); // 聚合状态摘要
  const [pollingInterval, setPollingInterval] = useState(null);

  useEffect(() => {
    if (user) {
      loadMaterials();
      loadTemplates();
    }
  }, [user]);

  // 清理轮询定时器
  useEffect(() => {
    return () => {
      if (pollingInterval) {
        clearInterval(pollingInterval);
      }
    };
  }, [pollingInterval]);

  const loadMaterials = async () => {
    // 使用当前登录用户的ID
    const userId = user?.id;
    if (!userId) {
      setMessage({ type: 'error', text: '请先登录' });
      return;
    }
    
    setLoading(true);
    try {
      // 获取原始素材（原图）- 对应素材库的"原始素材"标签页
      const originalResponse = await materialLibraryAPI.getMaterials(userId, 'original');
      console.log('原始素材API响应:', originalResponse);
      if (originalResponse.success) {
        const originalData = originalResponse.images.map(item => ({
          ...item,
          file_url: getImageUrl(item)
        }));
        setOriginalImages(originalData);
        console.log('原始素材数据:', originalData);
      }

      // 获取IP素材（人脸）- 对应素材库的"IP素材"标签页
      const faceResponse = await materialLibraryAPI.getMaterials(userId, 'face');
      console.log('IP素材API响应:', faceResponse);
      if (faceResponse.success) {
        const faceData = faceResponse.images.map(item => ({
          ...item,
          file_url: getImageUrl(item)
        }));
        setIpCharacters(faceData);
        console.log('IP素材数据:', faceData);
      }

      // 获取产品素材（服装）- 对应素材库的"产品素材"标签页，但API类型是'cloth'
      const clothResponse = await materialLibraryAPI.getMaterials(userId, 'cloth');
      console.log('产品素材API响应:', clothResponse);
      if (clothResponse.success) {
        const clothData = clothResponse.images.map(item => ({
          ...item,
          file_url: getImageUrl(item)
        }));
        setClothingItems(clothData);
        console.log('产品素材数据:', clothData);
      }
    } catch (error) {
      console.error('加载素材失败:', error);
      setMessage({ type: 'error', text: '加载素材失败，请稍后重试' });
    } finally {
      setLoading(false);
    }
  };

  // 获取图片URL
  const getImageUrl = (item) => {
    if (!item.stored_path) return '';
    const filename = item.stored_path.split(/[\\/]/).pop();
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
    return `${baseURL}/materials/${filename}`;
  };

  const loadTemplates = async () => {
    const userId = user?.id;
    if (!userId) {
      setMessage({ type: 'error', text: '请先登录' });
      return;
    }
    try {
      const [sceneResp, copyResp] = await Promise.all([
        textTemplateAPI.getTextTemplates(userId, 'prompt', 1, 100),
        textTemplateAPI.getTextTemplates(userId, 'copywrite', 1, 100),
      ]);

      const mapTemplates = (resp) => (resp && resp.success && Array.isArray(resp.templates)
        ? resp.templates.map(t => ({
            id: t.id,
            name: t.text_name,
            tag: t.text_label,
            created_date: t.created_at,
            content: t.text_content,
          }))
        : []);

      setSceneTemplates(mapTemplates(sceneResp));
      setCopyTemplates(mapTemplates(copyResp));
    } catch (error) {
      console.error('加载模板失败:', error);
      setMessage({ type: 'error', text: '加载模板失败，请稍后重试' });
    }
  };

  // 轮询多个任务状态并聚合进度
  const pollAllTasksStatus = async (taskIds) => {
    try {
      if (!taskIds || taskIds.length === 0) return;
      const responses = await Promise.allSettled(taskIds.map(id => aiSwapAPI.getTaskStatus(id)));
      const fulfilled = responses
        .filter(r => r.status === 'fulfilled')
        .map(r => r.value);
      const rejected = responses.filter(r => r.status === 'rejected');

      const total = taskIds.length;
      const completed = fulfilled.filter(r => r.status === 'completed').length;
      const failed = fulfilled.filter(r => r.status === 'failed').length + rejected.length;
      const processing = fulfilled.filter(r => r.status === 'processing').length;
      const pending = total - completed - failed - processing;

      // 聚合进度（平均）
      const avgProgress = fulfilled.length > 0
        ? Math.round(
            fulfilled.reduce((sum, r) => sum + (typeof r.progress === 'number' ? r.progress : 0), 0) / fulfilled.length
          )
        : 0;

      setGenerationProgress(avgProgress);
      setTaskStatus({
        total,
        completed,
        failed,
        processing,
        pending,
        details: fulfilled
      });

      if (completed + failed === total) {
        setCurrentTask('生成完成');
        setMessage({ type: failed === 0 ? 'success' : 'error', text: failed === 0 ? '全部生成完成！' : `部分失败：成功 ${completed}，失败 ${failed}` });
        setIsGenerating(false);
        if (pollingInterval) {
          clearInterval(pollingInterval);
          setPollingInterval(null);
        }
      } else if (processing > 0 || pending > 0) {
        setCurrentTask('AI处理中...');
      }
    } catch (error) {
      console.error('轮询任务状态失败:', error);
      setMessage({ type: 'error', text: '获取任务状态失败' });
    }
  };

  const handleSelection = (setter, selectedItems, id) => {
    setter(prev => {
      if (prev.includes(id)) {
        return prev.filter(item => item !== id);
      } else {
        return [...prev, id];
      }
    });
  };

  const handleTaskTypeToggle = (taskType) => {
    setSelectedTaskTypes(prev => {
      if (prev.includes(taskType)) {
        return prev.filter(type => type !== taskType);
      } else {
        return [...prev, taskType];
      }
    });
  };

  // 全选/取消全选操作
  const toggleSelectAllOriginals = () => {
    if (originalImages.length > 0 && selectedOriginalImages.length === originalImages.length) {
      setSelectedOriginalImages([]);
    } else {
      setSelectedOriginalImages(originalImages.map(item => item.id));
    }
  };

  const toggleSelectAllIp = () => {
    if (ipCharacters.length > 0 && selectedIpCharacters.length === ipCharacters.length) {
      setSelectedIpCharacters([]);
    } else {
      setSelectedIpCharacters(ipCharacters.map(item => item.id));
    }
  };

  const toggleSelectAllClothing = () => {
    if (clothingItems.length > 0 && selectedClothingItems.length === clothingItems.length) {
      setSelectedClothingItems([]);
    } else {
      setSelectedClothingItems(clothingItems.map(item => item.id));
    }
  };

  const toggleSelectAllTaskTypes = () => {
    const allTypes = ['换脸', '换衣', '换景'];
    if (selectedTaskTypes.length === allTypes.length) {
      setSelectedTaskTypes([]);
    } else {
      setSelectedTaskTypes(allTypes);
    }
  };

  const toggleSelectAllScenes = () => {
    if (sceneTemplates.length > 0 && selectedSceneTemplates.length === sceneTemplates.length) {
      setSelectedSceneTemplates([]);
    } else {
      setSelectedSceneTemplates(sceneTemplates.map(t => t.id));
    }
  };

  const toggleSelectAllCopies = () => {
    if (copyTemplates.length > 0 && selectedCopyTemplates.length === copyTemplates.length) {
      setSelectedCopyTemplates([]);
    } else {
      setSelectedCopyTemplates(copyTemplates.map(t => t.id));
    }
  };

  // 取消当前任务
  const handleCancelTask = async () => {
    if (!currentTaskIds || currentTaskIds.length === 0) return;
    try {
      await Promise.allSettled(currentTaskIds.map(id => aiSwapAPI.cancelTask(id)));
      setMessage({ type: 'success', text: '已取消全部任务' });
      setIsGenerating(false);
      setCurrentTaskId(null);
      setCurrentTaskIds([]);
      setTaskStatus(null);
      if (pollingInterval) {
        clearInterval(pollingInterval);
        setPollingInterval(null);
      }
    } catch (error) {
      console.error('取消任务失败:', error);
      setMessage({ type: 'error', text: '取消任务失败' });
    }
  };

  const handleGenerate = async () => {
    // 验证用户登录状态
    if (!user?.id) {
      setMessage({ type: 'error', text: '请先登录' });
      return;
    }

    // 根据生成类型决定不同的处理逻辑
    if (generationType === 'video') {
      return await handleVideoGeneration();
    }

    // 原有的图片生成逻辑
    return await handleImageGeneration();
  };

  // 新增：视频生成处理函数
  const handleVideoGeneration = async () => {
    // 视频生成需要：原图 + 场景模板（作为动作模板）或自由提示
    const hasOriginal = selectedOriginalImages.length > 0;
    const hasSceneOrPrompt = selectedSceneTemplates.length > 0 || freePrompt.trim() !== '';

    if (!hasOriginal) {
      setMessage({ type: 'error', text: '视频生成：请选择至少一个原图' });
      return;
    }
    if (!hasSceneOrPrompt) {
      setMessage({ type: 'error', text: '视频生成：请选择至少一个场景模板或输入自由提示' });
      return;
    }

    setIsGenerating(true);
    setGenerationProgress(0);
    setMessage(null);
    setCurrentTaskId(null);
    setTaskStatus(null);

    try {
      const userId = user.id;
      const submittedTaskIds = [];

      const selectedOriginals = originalImages.filter(item => selectedOriginalImages.includes(item.id));
      
      // 处理场景模板：如果有自由提示，就使用自由提示；否则使用选中的场景模板
      let scenePrompts = [];
      if (freePrompt.trim()) {
        scenePrompts = [{ content: freePrompt.trim() }];
      } else {
        scenePrompts = sceneTemplates.filter(item => selectedSceneTemplates.includes(item.id));
      }
      
      const selectedCopies = selectedCopyTemplates.length > 0
        ? copyTemplates.filter(item => selectedCopyTemplates.includes(item.id))
        : [null];

      const totalCombos = selectedOriginals.length * scenePrompts.length * selectedCopies.length;
      console.log(`即将提交视频生成任务数量: ${totalCombos}`);

      for (const orig of selectedOriginals) {
        for (const scene of scenePrompts) {
          for (const copy of selectedCopies) {
            let prompt = '图生视频';
            if (scene) {
              prompt += `，场景/动作：${scene.content}`;
            }
            if (copy) {
              prompt += `，文案风格：${copy.content}`;
            }
            if (taskName.trim()) {
              prompt += `，任务：${taskName.trim()}`;
            }

            const videoData = {
              user_id: userId,
              image_id: orig.id,
              prompt,
              quantity: quantityPerGroup,
            };

            const resp = await aiGenVideoAPI.processGenVideo(videoData);
            if (resp && resp.success === true && resp.task_id) {
              submittedTaskIds.push(resp.task_id);
            } else {
              console.warn('视频生成任务提交失败:', resp);
            }
          }
        }
      }

      if (submittedTaskIds.length > 0) {
        setCurrentTaskIds(submittedTaskIds);
        setCurrentTaskId(submittedTaskIds[0]);
        setMessage({ type: 'success', text: `已提交 ${submittedTaskIds.length} 个视频生成任务，处理中...` });
        setCurrentTask('准备素材');
        setGenerationProgress(5);

        const interval = setInterval(() => {
          pollAllTasksStatus(submittedTaskIds);
        }, 2000);
        setPollingInterval(interval);
        pollAllTasksStatus(submittedTaskIds);
      } else {
        setIsGenerating(false);
        setMessage({ type: 'error', text: '未能成功提交任何任务，请稍后重试' });
      }
    } catch (error) {
      setIsGenerating(false);
      console.error('视频生成任务请求异常:', error);
      const errorMsg = error.message || '处理失败，请稍后重试';
      setMessage({ type: 'error', text: errorMsg });
    }
  };

  // 原有的图片生成函数重命名
  const handleImageGeneration = async () => {
    // 判定模式：换景 或 换脸换装
    const isBgMode = selectedTaskTypes.includes('换景') && !selectedTaskTypes.includes('换脸');
    const hasOriginal = selectedOriginalImages.length > 0;
    const hasScene = selectedSceneTemplates.length > 0;
    const hasFace = selectedIpCharacters.length > 0;
    const hasCloth = selectedClothingItems.length > 0;
    const isClothMode = selectedTaskTypes.includes('换衣') && !selectedTaskTypes.includes('换脸');
    const isFaceMode = selectedTaskTypes.includes('换脸') && !selectedTaskTypes.includes('换衣')
    const isFaceClothMode = selectedTaskTypes.includes('换脸') && selectedTaskTypes.includes('换衣');

    // 校验：按模式分别校验
    if (isBgMode) {
      if (!hasOriginal) {
        setMessage({ type: 'error', text: '换景：请选择至少一个原图' });
        return;
      }
      if (!hasScene && !freePrompt.trim()) {
        setMessage({ type: 'error', text: '换景：请选择至少一个场景模板或输入自由提示' });
        return;
      }
    } else if (isFaceClothMode) {
      if (!hasFace) {
        setMessage({ type: 'error', text: '换脸换装：请选择至少一个IP形象' });
        return;
      }
      if (!hasCloth) {
        setMessage({ type: 'error', text: '换脸换装：请选择至少一件服装' });
        return;
      }
      if (!hasScene && !freePrompt.trim()) {
        setMessage({ type: 'error', text: '换脸换装：请选择至少一个场景模板或输入自由提示' });
        return;
      }
    } else if (isClothMode) {
      if (!hasOriginal) {
        setMessage({ type: 'error', text: '换衣：请选择至少一个原图' });
        return;
      }
      if (!hasCloth) {
        setMessage({ type: 'error', text: '换衣：请选择至少一件服装' });
        return;
      }
    } else if (isFaceMode) {
      if (!hasOriginal) {
        setMessage({ type: 'error', text: '换脸：请选择至少一个原图'});
        return;
      }
      if (!hasFace) {
        setMessage({ type: 'error', text: '换脸：请至少选择一个人脸'});
        return;
      }
    } else {
      setMessage({ type: 'error', text: '请选择任务类型：换景 或 同时选择换脸和换衣' });
      return;
    }

    setIsGenerating(true);
    setGenerationProgress(0);
    setMessage(null);
    setCurrentTaskId(null);
    setTaskStatus(null);

    try {
      // 使用当前登录用户的ID
      const userId = user.id;

      const submittedTaskIds = [];

      if (isBgMode) {
        // 换景：原图 × 场景 × 文案
        const selectedOriginals = originalImages.filter(item => selectedOriginalImages.includes(item.id));
        
        // 处理场景模板：如果有自由提示，就使用自由提示；否则使用选中的场景模板
        let scenePrompts = [];
        if (freePrompt.trim()) {
          scenePrompts = [{ content: freePrompt.trim() }];
        } else {
          scenePrompts = sceneTemplates.filter(item => selectedSceneTemplates.includes(item.id));
        }
        
        const selectedCopies = selectedCopyTemplates.length > 0
          ? copyTemplates.filter(item => selectedCopyTemplates.includes(item.id))
          : [null];

        if (selectedOriginals.length === 0 || scenePrompts.length === 0) {
          throw new Error('选中的原图/场景不存在');
        }

        const totalCombos = selectedOriginals.length * scenePrompts.length * selectedCopies.length;
        console.log(`即将提交换景任务数量: ${totalCombos}`);

        for (const orig of selectedOriginals) {
          for (const scene of scenePrompts) {
            for (const copy of selectedCopies) {
              let prompt = 'AI换景';
              if (scene) {
                prompt += `，场景：${scene.content}`;
              }
              if (copy) {
                prompt += `，文案风格：${copy.content}`;
              }
              if (taskName.trim()) {
                prompt += `，任务：${taskName.trim()}`;
              }

              const swapBgData = {
                user_id: userId,
                image_id: orig.id,
                prompt,
                quantity: quantityPerGroup,
              };

              const resp = await aiSwapBgAPI.processSwapBg(swapBgData);
              if (resp && resp.success === true && resp.task_id) {
                submittedTaskIds.push(resp.task_id);
              } else {
                console.warn('换景任务提交失败:', resp);
              }
            }
          }
        }
      } else if (isFaceClothMode) {
        // 换脸换装：人脸 × 服装 × 场景 × 文案
        const selectedFaces = ipCharacters.filter(item => selectedIpCharacters.includes(item.id));
        const selectedClothes = clothingItems.filter(item => selectedClothingItems.includes(item.id));
        
        // 处理场景模板：如果有自由提示，就使用自由提示；否则使用选中的场景模板
        let scenePrompts = [];
        if (freePrompt.trim()) {
          scenePrompts = [{ content: freePrompt.trim() }];
        } else {
          scenePrompts = sceneTemplates.filter(item => selectedSceneTemplates.includes(item.id));
        }
        
        const selectedCopies = selectedCopyTemplates.length > 0
          ? copyTemplates.filter(item => selectedCopyTemplates.includes(item.id))
          : [null];

        if (selectedFaces.length === 0 || selectedClothes.length === 0 || scenePrompts.length === 0) {
          throw new Error('选中的素材/模板不存在');
        }

        const totalCombos = selectedFaces.length * selectedClothes.length * scenePrompts.length * selectedCopies.length;
        console.log(`即将提交组合任务数量: ${totalCombos}`);

        for (const face of selectedFaces) {
          for (const cloth of selectedClothes) {
            for (const scene of scenePrompts) {
              for (const copy of selectedCopies) {
                let prompt = 'AI换脸换装';
                if (scene) {
                  prompt += `，场景：${scene.content}`;
                }
                if (copy) {
                  prompt += `，文案风格：${copy.content}`;
                }
                if (taskName.trim()) {
                  prompt += `，任务：${taskName.trim()}`;
                }

                const swapData = {
                  user_id: userId,
                  face_image_id: face.id,
                  cloth_image_id: cloth.id,
                  prompt,
                  quantity: quantityPerGroup,
                };
                
                const resp = await aiSwapAPI.processSwap(swapData);
                if (resp && resp.success === true && resp.task_id) {
                  submittedTaskIds.push(resp.task_id);
                } else {
                  console.warn('组合任务提交失败:', resp);
                }
              }
            }
          }
        }
      } else if (isClothMode) {
        // 换衣：原图 x 服装
        const selectedOriginals = originalImages.filter(item => selectedOriginalImages.includes(item.id));
        const selectedClothes = clothingItems.filter(item => selectedClothingItems.includes(item.id));
        const selectedCopies = selectedCopyTemplates.length > 0
            ? copyTemplates.filter(item => selectedCopyTemplates.includes(item.id))
            : [null];

        if (selectedOriginals.length === 0 || selectedClothes.length === 0) {
            throw new Error('选中的原图/服装不存在');
        }

        const totalCombos = selectedOriginals.length * selectedClothes.length;
        console.log(`即将提交换衣任务数量: ${totalCombos}`);

        for (const orig of selectedOriginals) {
            for (const cloth of selectedClothes) {
                for (const copy of selectedCopies) {
                    let prompt = "AI换衣服";
                    if (copy) {
                        prompt += `文案风格：${copy.content}`;
                    }
                    if (taskName.trim()) {
                        prompt += `，任务：${taskName.trim()}`;
                    }

                    const swapClothData = {
                        user_id: userId, 
                        raw_image_id: orig.id,
                        cloth_image_id: cloth.id,
                        quantity: quantityPerGroup,
                    };

                    const resp = await aiSwapClothAPI.processSwapCloth(swapClothData);
                    if (resp && resp.success === true && resp.task_id) {
                        submittedTaskIds.push(resp.task_id);
                    } else {
                        console.warn('换衣任务提交失败:', resp);
                    }

                }
            }
        }
      } else if (isFaceMode) {
        // 换脸： 原图 x IP
        const selectedOriginals = originalImages.filter(item => selectedOriginalImages.includes(item.id));
        const selectedFaces = ipCharacters.filter(item => selectedIpCharacters.includes(item.id));
        const selectedCopies = selectedCopyTemplates.length > 0
            ? copyTemplates.filter(item => selectedCopyTemplates.includes(item.id))
            : [null];

        if (selectedOriginals.length === 0 || selectedFaces.length === 0) {
            throw new Error('选中的原图/IP不存在');
        }

        const totalCombos = selectedOriginals.length * selectedFaces.length;
        console.log(`即将提交换脸任务数量：${totalCombos}`);

        for (const orig of selectedOriginals) {
            for (const face of selectedFaces) {
                for (const copy of selectedCopies) {
                    let prompt = "AI换脸";
                    if (copy) {
                        prompt +=  `文案风格：${copy.content}`;
                    }
                    if (taskName.trim()) {
                        prompt += `，任务：${taskName.trim()}`;
                    }

                    const swapFaceData = {
                        user_id: userId,
                        raw_image_id: orig.id,
                        face_image_id: face.id,
                        quantity: quantityPerGroup,
                    }

                    const resp = await aiSwapFaceAPI.processSwapFace(swapFaceData);
                    if (resp && resp.success === true && resp.task_id) {
                        submittedTaskIds.push(resp.task_id);
                    } else {
                        console.warn('换脸任务提交失败：', resp);
                    }
                }
            }
        }
      }

      if (submittedTaskIds.length > 0) {
        setCurrentTaskIds(submittedTaskIds);
        setCurrentTaskId(submittedTaskIds[0]);
        setMessage({ type: 'success', text: `已提交 ${submittedTaskIds.length} 个任务，处理中...` });
        setCurrentTask('准备素材');
        setGenerationProgress(5);

        const interval = setInterval(() => {
          pollAllTasksStatus(submittedTaskIds);
        }, 2000);
        setPollingInterval(interval);
        // 立即轮询一次
        pollAllTasksStatus(submittedTaskIds);
      } else {
        setIsGenerating(false);
        setMessage({ type: 'error', text: '未能成功提交任何任务，请稍后重试' });
      }
      
    } catch (error) {
      setIsGenerating(false);
      console.error('生成任务请求异常:', error);
      const errorMsg = error.message || '处理失败，请稍后重试';
      setMessage({ type: 'error', text: errorMsg });
    }
  };

  // 生成按钮的启用状态判断
  const hasSceneOrFreePrompt = selectedSceneTemplates.length > 0 || freePrompt.trim() !== ''; // 场景模板或自由提示
  const canGenerateBg = selectedTaskTypes.includes('换景') && selectedOriginalImages.length > 0 && hasSceneOrFreePrompt && !isGenerating;
  const canGenerateFaceCloth = selectedTaskTypes.includes('换脸') && selectedTaskTypes.includes('换衣')  && selectedIpCharacters.length > 0 && selectedClothingItems.length > 0 && hasSceneOrFreePrompt && !isGenerating;
  const canGenerateCloth = selectedTaskTypes.includes('换衣') && !selectedTaskTypes.includes('换脸') && selectedOriginalImages.length > 0 && selectedClothingItems.length > 0 && !isGenerating;
  const canGenerateFace = selectedTaskTypes.includes('换脸') && !selectedTaskTypes.includes('换衣') && selectedOriginalImages.length > 0 && selectedIpCharacters.length > 0 && !isGenerating;
  const canGenerateVideo = generationType === 'video' && selectedOriginalImages.length > 0 && hasSceneOrFreePrompt && !isGenerating; // 视频生成条件
  
  const canGenerate = generationType === 'video' 
    ? canGenerateVideo 
    : (canGenerateBg || canGenerateFaceCloth || canGenerateCloth || canGenerateFace);
  const totalSelected = selectedIpCharacters.length + selectedClothingItems.length;

  // 高亮：根据选择的任务类型和生成类型提示需要选择哪些素材（当该类素材未选择时闪烁提示）
  let requireOriginal, requireFace, requireCloth, requireScene, requireCopy;
  let highlightOriginal, highlightFace, highlightCloth, highlightScene, highlightCopy;

  if (generationType === 'video') {
    // 视频生成模式：需要原图、场景模板或自由提示、文案模板
    requireOriginal = true;
    requireFace = false;
    requireCloth = false;
    requireScene = true;
    requireCopy = true;

    highlightOriginal = requireOriginal && selectedOriginalImages.length === 0;
    highlightFace = false;
    highlightCloth = false;
    highlightScene = requireScene && selectedSceneTemplates.length === 0 && freePrompt.trim() === '';
    highlightCopy = requireCopy && selectedCopyTemplates.length === 0;
  } else {
    // 图片生成模式：原有逻辑
    requireOriginal = selectedTaskTypes.includes('换景') && !selectedTaskTypes.includes('换脸') && !selectedTaskTypes.includes('换衣')
      || (selectedTaskTypes.includes('换衣') && !selectedTaskTypes.includes('换脸'))
      || (selectedTaskTypes.includes('换脸') && !selectedTaskTypes.includes('换衣'));

    requireFace = selectedTaskTypes.includes('换脸');
    requireCloth = selectedTaskTypes.includes('换衣');
    requireScene = selectedTaskTypes.includes('换景')
      || (selectedTaskTypes.includes('换脸') && selectedTaskTypes.includes('换衣'));
    requireCopy = requireScene;

    highlightOriginal = requireOriginal && selectedOriginalImages.length === 0;
    highlightFace = requireFace && selectedIpCharacters.length === 0;
    highlightCloth = requireCloth && selectedClothingItems.length === 0;
    highlightScene = requireScene && selectedSceneTemplates.length === 0 && freePrompt.trim() === '';
    highlightCopy = requireCopy && selectedCopyTemplates.length === 0;
  }

  return (
    <div className="min-h-screen bg-slate-50">
      {/* 顶部标题栏 */}
      <div className="bg-white border-b border-slate-200 px-6 py-4">
        <div className="max-w-7xl mx-auto">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-slate-900">智能生成</h1>
              <p className="text-slate-600 text-sm mt-1">
                选择素材和模板，使用ComfyUI一键生成营销内容
              </p>
            </div>
            <Button
              onClick={handleGenerate}
              disabled={!canGenerate}
              size="lg"
              className="bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white px-8"
            >
              {isGenerating ? (
                <>
                  <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                  生成中...
                </>
              ) : (
                <>
                  <Play className="w-5 h-5 mr-2" />
                  开始{generationType === 'video' ? '视频' : '图片'}生成
                </>
              )}
            </Button>
          </div>
        </div>
      </div>

      {/* 消息提示 */}
      {message && (
        <div className="px-6 py-2">
          <Alert className={`${message.type === 'error' ? 'border-red-200 bg-red-50 text-red-700' : 'border-green-200 bg-green-50 text-green-700'}`}>
            <AlertDescription>{message.text}</AlertDescription>
          </Alert>
        </div>
      )}

      {/* 主要内容区域 */}
      <div className="max-w-7xl mx-auto px-6 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          
          {/* 第一栏：选择原图 */}
          <Card className={`h-fit ${highlightOriginal ? 'animate-pulse ring-2 ring-amber-400' : ''}`}>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-lg">
                <Camera className="w-5 h-5" />
                原图
                <div className="ml-auto flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={toggleSelectAllOriginals}
                    disabled={originalImages.length === 0}
                  >
                    {originalImages.length > 0 && selectedOriginalImages.length === originalImages.length ? '取消全选' : '全选'}
                  </Button>
                  <Badge variant="secondary">
                    {selectedOriginalImages.length}
                  </Badge>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="text-center py-8">
                  <Loader2 className="w-8 h-8 mx-auto mb-3 animate-spin text-slate-400" />
                  <p className="text-sm text-slate-500">加载中...</p>
                </div>
              ) : originalImages.length > 0 ? (
                <ScrollArea className="h-[526px]">
                  <div className="grid grid-cols-1 gap-4 pr-2">
                    {originalImages.map((image) => (
                      <MaterialCard
                        key={image.id}
                        item={image}
                        isSelected={selectedOriginalImages.includes(image.id)}
                        onSelect={(id) => handleSelection(setSelectedOriginalImages, selectedOriginalImages, id)}
                      />
                    ))}
                  </div>
                </ScrollArea>
              ) : (
                <div className="text-center py-8 text-slate-500">
                  <ImageIcon className="w-12 h-12 mx-auto mb-3 text-slate-300" />
                  <p className="text-sm">暂无原图</p>
                  <p className="text-xs mt-1">请先到素材库上传</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 第二栏：选择IP形象 */}
          <Card className={`h-fit ${highlightFace ? 'animate-pulse ring-2 ring-amber-400' : ''}`}>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-lg">
                <User className="w-5 h-5" />
                IP形象
                <div className="ml-auto flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={toggleSelectAllIp}
                    disabled={ipCharacters.length === 0}
                  >
                    {ipCharacters.length > 0 && selectedIpCharacters.length === ipCharacters.length ? '取消全选' : '全选'}
                  </Button>
                  <Badge variant="secondary">
                    {selectedIpCharacters.length}
                  </Badge>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="text-center py-8">
                  <Loader2 className="w-8 h-8 mx-auto mb-3 animate-spin text-slate-400" />
                  <p className="text-sm text-slate-500">加载中...</p>
                </div>
              ) : ipCharacters.length > 0 ? (
                <ScrollArea className="h-[526px]">
                  <div className="grid grid-cols-1 gap-4 pr-2">
                    {ipCharacters.map((character) => (
                      <MaterialCard
                        key={character.id}
                        item={character}
                        isSelected={selectedIpCharacters.includes(character.id)}
                        onSelect={(id) => handleSelection(setSelectedIpCharacters, selectedIpCharacters, id)}
                      />
                    ))}
                  </div>
                </ScrollArea>
              ) : (
                <div className="text-center py-8 text-slate-500">
                  <User className="w-12 h-12 mx-auto mb-3 text-slate-300" />
                  <p className="text-sm">暂无IP形象</p>
                  <p className="text-xs mt-1">请先到素材库上传</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 第三栏：选择服装 */}
          <Card className={`h-fit ${highlightCloth ? 'animate-pulse ring-2 ring-amber-400' : ''}`}>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-lg">
                <Shirt className="w-5 h-5" />
                服装
                <div className="ml-auto flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={toggleSelectAllClothing}
                    disabled={clothingItems.length === 0}
                  >
                    {clothingItems.length > 0 && selectedClothingItems.length === clothingItems.length ? '取消全选' : '全选'}
                  </Button>
                  <Badge variant="secondary">
                    {selectedClothingItems.length}
                  </Badge>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="text-center py-8">
                  <Loader2 className="w-8 h-8 mx-auto mb-3 animate-spin text-slate-400" />
                  <p className="text-sm text-slate-500">加载中...</p>
                </div>
              ) : clothingItems.length > 0 ? (
                <ScrollArea className="h-[526px]">
                  <div className="grid grid-cols-1 gap-4 pr-2">
                    {clothingItems.map((clothing) => (
                      <MaterialCard
                        key={clothing.id}
                        item={clothing}
                        isSelected={selectedClothingItems.includes(clothing.id)}
                        onSelect={(id) => handleSelection(setSelectedClothingItems, selectedClothingItems, id)}
                      />
                    ))}
                  </div>
                </ScrollArea>
              ) : (
                <div className="text-center py-8 text-slate-500">
                  <Shirt className="w-12 h-12 mx-auto mb-3 text-slate-300" />
                  <p className="text-sm">暂无服装</p>
                  <p className="text-xs mt-1">请先到素材库上传</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 第四栏：生成配置 */}
          <Card className="h-fit" style={{color: 'black'}}>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-lg">
                <Settings className="w-5 h-5" />
                生成配置
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* 生成类型 */}
              <div>
                <Label className="text-sm font-bold mb-3 block">生成类型</Label>
                <div className="flex gap-2">
                  <Button
                    variant={generationType === 'image' ? 'default' : 'outline'}
                    onClick={() => setGenerationType('image')}
                    className="flex-1 py-2"
                  >
                    图片
                  </Button>
                  <Button
                    variant={generationType === 'video' ? 'default' : 'outline'}
                    onClick={() => setGenerationType('video')}
                    className="flex-1 py-2"
                  >
                    视频
                  </Button>
                </div>
              </div>

              {/* 任务命名 */}
              <div>
                <Label htmlFor="taskName" className="text-sm font-bold">任务命名</Label>
                <div className="relative mt-2">
                  <Input
                    id="taskName"
                    value={taskName}
                    onChange={(e) => setTaskName(e.target.value)}
                    placeholder="输入任务名称..."
                    className="pr-8"
                  />
                  <FileText className="w-4 h-4 absolute right-2 top-1/2 transform -translate-y-1/2 text-slate-400" />
                </div>
              </div>

              {/* 任务类型 - 仅在图片生成模式下显示 */}
              {generationType === 'image' && (
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <Label className="text-sm font-bold">任务类型</Label>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={toggleSelectAllTaskTypes}
                    >
                      {selectedTaskTypes.length === 3 ? '取消全选' : '全选'}
                    </Button>
                  </div>
                  <div className="flex items-center gap-4">
                    {['换脸', '换衣', '换景'].map((taskType) => (
                      <div key={taskType} className="flex items-center space-x-2">
                        <input
                          type="checkbox"
                          id={taskType}
                          checked={selectedTaskTypes.includes(taskType)}
                          onChange={() => handleTaskTypeToggle(taskType)}
                          className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
                        />
                        <Label htmlFor={taskType} className="text-sm cursor-pointer">
                          {taskType}
                        </Label>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 每组生成数量 */}
              <div>
                <Label htmlFor="quantity" className="text-sm font-bold">每组生成数量</Label>
                <Input
                  id="quantity"
                  type="number"
                  min="1"
                  max="10"
                  value={quantityPerGroup}
                  onChange={(e) => setQuantityPerGroup(parseInt(e.target.value) || 1)}
                  className="mt-2 w-full"
                />
              </div>

              {/* 自由提示 */}
              <div>
                <Label htmlFor="freePrompt" className="text-sm font-bold">自由提示</Label>
                <div className="relative mt-2">
                  <Input
                    id="freePrompt"
                    value={freePrompt}
                    onChange={(e) => setFreePrompt(e.target.value)}
                    placeholder="输入自定义生成提示词..."
                    className="pr-8"
                  />
                  <Wand2 className="w-4 h-4 absolute right-2 top-1/2 transform -translate-y-1/2 text-slate-400" />
                </div>
              </div>

              {/* 场景模板 */}
              <div className={highlightScene ? 'animate-pulse' : ''}>
                <div className={`flex items-center justify-between mb-2 ${highlightScene ? 'text-amber-600' : ''}`}>
                  <Label className="text-sm font-bold">场景模板</Label>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={toggleSelectAllScenes}
                      disabled={sceneTemplates.length === 0}
                    >
                      {sceneTemplates.length > 0 && selectedSceneTemplates.length === sceneTemplates.length ? '取消全选' : '全选'}
                    </Button>
                    <Badge variant="secondary" className="text-xs">
                      {selectedSceneTemplates.length}
                    </Badge>
                  </div>
                </div>
                <ScrollArea className={`h-20 ${highlightScene ? 'ring-1 ring-amber-400 rounded-md' : ''}`}>
                  <div className="space-y-2">
                    {sceneTemplates.map((template) => (
                      <TemplateItem
                        key={template.id}
                        template={template}
                        isSelected={selectedSceneTemplates.includes(template.id)}
                        onSelect={(id) => handleSelection(setSelectedSceneTemplates, selectedSceneTemplates, id)}
                        type="scene"
                      />
                    ))}
                  </div>
                </ScrollArea>
              </div>

              {/* 文案模板 */}
              <div className={highlightCopy ? 'animate-pulse' : ''}>
                <div className={`flex items-center justify-between mb-2 ${highlightCopy ? 'text-amber-600' : ''}`}>
                  <Label className="text-sm font-bold">文案模板</Label>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={toggleSelectAllCopies}
                      disabled={copyTemplates.length === 0}
                    >
                      {copyTemplates.length > 0 && selectedCopyTemplates.length === copyTemplates.length ? '取消全选' : '全选'}
                    </Button>
                    <Badge variant="secondary" className="text-xs">
                      {selectedCopyTemplates.length}
                    </Badge>
                  </div>
                </div>
                <ScrollArea className={`h-20 ${highlightCopy ? 'ring-1 ring-amber-400 rounded-md' : ''}`}>
                  <div className="space-y-2">
                    {copyTemplates.map((template) => (
                      <TemplateItem
                        key={template.id}
                        template={template}
                        isSelected={selectedCopyTemplates.includes(template.id)}
                        onSelect={(id) => handleSelection(setSelectedCopyTemplates, selectedCopyTemplates, id)}
                        type="copy"
                      />
                    ))}
                  </div>
                </ScrollArea>
              </div>

            </CardContent>
          </Card>

        </div>

        {/* 生成进度 */}
        {isGenerating && (
          <Card className="mt-6">
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Loader2 className="w-5 h-5 animate-spin" />
                  生成进度
                </div>
                {currentTaskIds && currentTaskIds.length > 0 && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleCancelTask}
                    className="text-red-600 hover:text-red-700 hover:bg-red-50"
                  >
                    取消任务
                  </Button>
                )}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-sm font-medium">{currentTask}</span>
                  <span className="text-sm text-slate-500">{generationProgress}%</span>
                </div>
                <Progress value={generationProgress} className="w-full" />
                {currentTaskIds && currentTaskIds.length > 0 && (
                  <div className="text-xs text-slate-500 space-y-1">
                    <div>任务数: {currentTaskIds.length}</div>
                    <div>示例任务ID: {currentTaskIds[0]}</div>
                    {taskStatus && (
                      <div className="flex flex-wrap gap-3">
                        <span>完成: {taskStatus.completed}</span>
                        <span>进行中: {taskStatus.processing}</span>
                        <span>等待: {taskStatus.pending}</span>
                        <span>失败: {taskStatus.failed}</span>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        )}

      </div>
    </div>
  );
}
