import { useCallback } from 'react';
import { useCanvasStore } from '../store/canvasStore';
import { ProcessingEngine } from '../services/processingEngine';
import { aiService } from '../services/aiServices';
import { DataFlow, NodeType } from '../types/canvas';

// 创建全局处理引擎实例
const processingEngine = new ProcessingEngine();

/**
 * 节点处理 Hook
 */
export const useNodeProcessing = () => {
  const {
    startProcessing,
    updateProgress,
    completeProcessing,
    errorProcessing,
    cancelProcessing,
    updateNode
  } = useCanvasStore();

  /**
   * 处理节点
   */
  const processNode = useCallback(async (
    nodeId: string,
    nodeType: NodeType,
    inputData: DataFlow
  ) => {
    try {
      // 开始处理
      startProcessing(nodeId);

      // 使用处理引擎处理节点
      const result = await processingEngine.processNode(nodeId, nodeType, inputData, {
        onProgress: (progress) => {
          updateProgress(nodeId, progress);
        },
        onComplete: (result) => {
          completeProcessing(nodeId, result);
          
          // 更新节点数据
          updateNode(nodeId, {
            data: (prevData: any) => ({
              ...prevData,
              result: result
            })
          });
        },
        onError: (error) => {
          errorProcessing(nodeId, error);
        }
      });

      return result;
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Processing failed';
      errorProcessing(nodeId, errorMessage);
      throw error;
    }
  }, [startProcessing, updateProgress, completeProcessing, errorProcessing, updateNode]);

  /**
   * 取消节点处理
   */
  const cancelNodeProcessing = useCallback((nodeId: string) => {
    processingEngine.cancelProcessing(nodeId);
    cancelProcessing(nodeId);
  }, [cancelProcessing]);

  /**
   * 检查节点是否正在处理
   */
  const isNodeProcessing = useCallback((nodeId: string) => {
    return processingEngine.isProcessing(nodeId);
  }, []);

  /**
   * 获取所有正在处理的节点
   */
  const getActiveProcesses = useCallback(() => {
    return processingEngine.getActiveProcesses();
  }, []);

  return {
    processNode,
    cancelNodeProcessing,
    isNodeProcessing,
    getActiveProcesses
  };
};

/**
 * 批量处理 Hook
 */
export const useBatchProcessing = () => {
  const { updateProgress, updateNode } = useCanvasStore();

  /**
   * 处理批量数据
   */
  const processBatch = useCallback(async (
    nodeId: string,
    items: any[],
    processType: 'prompt-optimize' | 'image-generate' | 'image-edit' | 'video-generate'
  ) => {
    try {
      const results = await aiService.processBatch(
        items,
        processType,
        (completed, total) => {
          const progress = (completed / total) * 100;
          updateProgress(nodeId, progress);
          
          // 更新节点显示的批量结果
          updateNode(nodeId, {
            data: (prevData: any) => ({
              ...prevData,
              results: items.slice(0, completed).map((item, index) => ({
                id: `item-${index}`,
                filename: item.filename || `Item ${index + 1}`,
                status: 'success',
                result: results[index],
                thumbnail: typeof results[index] === 'string' ? results[index] : undefined
              })),
              totalCount: total,
              completedCount: completed
            })
          });
        }
      );

      return results;
    } catch (error) {
      throw error;
    }
  }, [updateProgress, updateNode]);

  return {
    processBatch
  };
};

/**
 * 节点状态 Hook
 */
export const useNodeStatus = (nodeId: string) => {
  const { processingNodes } = useCanvasStore();
  const processingInfo = processingNodes.get(nodeId);

  return {
    status: processingInfo?.status || 'idle',
    progress: processingInfo?.progress || 0,
    error: processingInfo?.error,
    startTime: processingInfo?.startTime,
    estimatedTime: processingInfo?.estimatedTime
  };
};

/**
 * 连接验证 Hook
 */
export const useConnectionValidation = () => {
  const { nodes } = useCanvasStore();

  /**
   * 验证连接是否有效
   */
  const validateConnection = useCallback((connection: any) => {
    const sourceNode = nodes.find(n => n.id === connection.source);
    const targetNode = nodes.find(n => n.id === connection.target);

    if (!sourceNode || !targetNode || !sourceNode.type || !targetNode.type) return false;

    // 基本的类型兼容性检查
    const sourceType = getNodeOutputType(sourceNode.type);
    const targetType = getNodeInputType(targetNode.type);

    // 允许的连接类型
    const compatibleConnections = [
      ['text', 'text'],
      ['image', 'image'],
      ['video', 'video'],
      ['batch', 'batch'],
      ['text', 'batch'],  // 文本可以转为批量
      ['image', 'batch'], // 图片可以转为批量
      ['batch', 'text'],  // 批量可以取第一个作为单个
      ['batch', 'image']  // 批量可以取第一个作为单个
    ];

    return compatibleConnections.some(([src, tgt]) => 
      sourceType === src && targetType === tgt
    );
  }, [nodes]);

  return {
    validateConnection
  };
};

/**
 * 获取节点输出类型
 */
function getNodeOutputType(nodeType: string): string {
  switch (nodeType) {
    case 'textInput':
    case 'promptOptimize':
      return 'text';
    case 'imageUpload':
    case 'imageGenerate':
    case 'imageEdit':
      return 'image';
    case 'videoGenerate':
      return 'video';
    case 'folderUpload':
      return 'batch';
    default:
      return 'text';
  }
}

/**
 * 获取节点输入类型
 */
function getNodeInputType(nodeType: string): string {
  switch (nodeType) {
    case 'promptOptimize':
    case 'textDisplay':
      return 'text';
    case 'imageGenerate':
    case 'imageEdit':
    case 'imageDisplay':
      return 'image';
    case 'videoGenerate':
    case 'videoPlayer':
      return 'video';
    case 'batchGrid':
      return 'batch';
    default:
      return 'text';
  }
}
