'use client';

import React, { useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Layers,
  Play,
  X,
  Loader2,
  CheckCircle2,
  AlertCircle
} from 'lucide-react';
import { cn } from '@/utils';
import { useCanvasStore } from '@/lib/store/canvasStore';
import { BatchService } from '@/lib/api';
import { AppNodeType, NodeType } from '../types/node';

interface BatchGenerationToolbarProps {
  onClose: () => void;
}

export function BatchGenerationToolbar({ onClose }: BatchGenerationToolbarProps) {
  const [isGenerating, setIsGenerating] = useState(false);
  const [result, setResult] = useState<{
    success: boolean;
    message: string;
    taskCount?: number;
  } | null>(null);
  
  const nodes = useCanvasStore((state) => state.nodes);
  const selectedNodes = nodes.filter(n => n.selected);
  
  // 获取可生成的节点（有生成类型的节点）
  const generatableNodes = selectedNodes.filter(node => {
    if (node.type !== 'appNode') return false;
    const nodeData = node.data;
    return nodeData.type === NodeType.IMAGE_GENERATOR ||
           nodeData.type === NodeType.VIDEO_GENERATOR ||
           nodeData.type === NodeType.AUDIO_GENERATOR;
  });

  const handleBatchGenerate = useCallback(async () => {
    if (generatableNodes.length === 0) return;
    
    setIsGenerating(true);
    setResult(null);
    
    try {
      // 构建批量生成请求
      const items = generatableNodes.map(node => {
        const data = node.data;
        // 将 NodeType 映射为 API 类型
        const typeMap: Record<string, string> = {
          'IMAGE_GENERATOR': 'image',
          'VIDEO_GENERATOR': 'video',
          'AUDIO_GENERATOR': 'audio'
        };
        const type = data.outputType || typeMap[data.type] || 'image';

        return {
          type: type,
          prompt: data.prompt || data.title || '',
          model: data.model,
          aspect_ratio: data.aspectRatio || '16:9',
          resolution: data.resolution || '1K',
          duration: data.duration,
          voice: data.voice,
          image_inputs: data.imageInputs || [],
          extra_params: data.extraParams || {},
          source: 'canvas',
          source_id: node.id
        };
      });
      
      const job = await BatchService.createJob(items);

      setResult({
        success: job.status !== 'failed',
        message: `成功创建批量任务 (ID: ${job.id})`,
        taskCount: job.total
      });

      // 3秒后自动关闭
      if (job.status !== 'failed') {
        setTimeout(() => {
          onClose();
        }, 3000);
      }
    } catch (error) {
      console.error('Batch generation failed:', error);
      setResult({
        success: false,
        message: '批量生成失败，请重试'
      });
    } finally {
      setIsGenerating(false);
    }
  }, [generatableNodes, onClose]);

  return (
    <motion.div
      initial={{ opacity: 0, y: -20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -20 }}
      className="absolute top-4 left-1/2 -translate-x-1/2 z-[100] bg-black/80 backdrop-blur-xl border border-white/10 rounded-2xl shadow-2xl p-4 min-w-[400px]"
    >
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center">
            <Layers className="w-5 h-5 text-white" />
          </div>
          <div>
            <h3 className="text-white font-semibold">批量生成</h3>
            <p className="text-xs text-muted-foreground">
              已选择 {generatableNodes.length} 个生成节点
            </p>
          </div>
        </div>
        
        <button
          onClick={onClose}
          className="p-2 text-muted-foreground hover:text-white hover:bg-white/10 rounded-lg transition-colors"
        >
          <X className="w-4 h-4" />
        </button>
      </div>

      {/* 节点列表预览 */}
      {generatableNodes.length > 0 ? (
        <div className="max-h-[200px] overflow-y-auto space-y-2 mb-4">
          {generatableNodes.map((node, idx) => (
            <div
              key={node.id}
              className="flex items-center gap-3 p-2 bg-white/5 rounded-lg"
            >
              <span className="text-xs text-muted-foreground w-6">{idx + 1}</span>
              <span className="text-sm text-white truncate flex-1">
                {node.data.title || node.data.prompt || '未命名节点'}
              </span>
              <span className={cn(
                "text-xs px-2 py-0.5 rounded",
                node.data.outputType === 'image' || node.data.type === NodeType.IMAGE_GENERATOR
                  ? "bg-blue-500/20 text-blue-400"
                  : node.data.outputType === 'video' || node.data.type === NodeType.VIDEO_GENERATOR
                  ? "bg-purple-500/20 text-purple-400"
                  : node.data.outputType === 'audio' || node.data.type === NodeType.AUDIO_GENERATOR
                  ? "bg-green-500/20 text-green-400"
                  : "bg-yellow-500/20 text-yellow-400"
              )}>
                {node.data.outputType ? String(node.data.outputType) : String(node.data.type)}
              </span>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-center py-6 text-muted-foreground">
          <Layers className="w-12 h-12 mx-auto mb-3 opacity-20" />
          <p className="text-sm">没有选择可生成的节点</p>
          <p className="text-xs opacity-60">请选择包含生成配置的节点</p>
        </div>
      )}

      {/* 结果提示 */}
      {result && (
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className={cn(
            "p-3 rounded-lg mb-4 flex items-center gap-2",
            result.success 
              ? "bg-green-500/10 border border-green-500/30" 
              : "bg-red-500/10 border border-red-500/30"
          )}
        >
          {result.success ? (
            <CheckCircle2 className="w-5 h-5 text-green-400" />
          ) : (
            <AlertCircle className="w-5 h-5 text-red-400" />
          )}
          <span className={cn(
            "text-sm",
            result.success ? "text-green-400" : "text-red-400"
          )}>
            {result.message}
          </span>
        </motion.div>
      )}

      {/* 操作按钮 */}
      <div className="flex gap-3">
        <button
          onClick={onClose}
          className="flex-1 px-4 py-2 text-sm text-muted-foreground hover:text-white hover:bg-white/10 rounded-xl transition-colors"
        >
          取消
        </button>
        <button
          onClick={handleBatchGenerate}
          disabled={generatableNodes.length === 0 || isGenerating}
          className={cn(
            "flex-[2] flex items-center justify-center gap-2 px-4 py-2 text-sm font-medium rounded-xl transition-all",
            generatableNodes.length === 0 || isGenerating
              ? "bg-white/5 text-muted-foreground cursor-not-allowed"
              : "bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:opacity-90"
          )}
        >
          {isGenerating ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" />
              生成中...
            </>
          ) : (
            <>
              <Play className="w-4 h-4" />
              开始批量生成 ({generatableNodes.length})
            </>
          )}
        </button>
      </div>
    </motion.div>
  );
}