import React, { useEffect } from 'react';
import { BaseNode } from '../BaseNode';
import { NodePort, DataFlow } from '../../../types/canvas';
import { useNodeProcessing, useNodeStatus } from '../../../hooks/useNodeProcessing';

interface PromptOptimizeNodeProps {
  id: string;
  data: {
    inputPrompt?: string;
    optimizedPrompt?: string;
    result?: string;
  };
}

export const PromptOptimizeNode: React.FC<PromptOptimizeNodeProps> = ({ id, data }) => {
  const { processNode } = useNodeProcessing();
  const { status, progress } = useNodeStatus(id);

  const inputs: NodePort[] = [
    { id: 'text-input', type: 'text', label: '原始提示词', position: 'input' }
  ];

  const outputs: NodePort[] = [
    { id: 'text-output', type: 'text', label: '优化提示词', position: 'output' }
  ];

  // 监听输入数据变化并处理
  useEffect(() => {
    if (data.inputPrompt && data.inputPrompt !== data.result && status !== 'loading') {
      const inputData: DataFlow = {
        type: 'single',
        dataType: 'text',
        content: data.inputPrompt
      };

      processNode(id, 'promptOptimize', inputData).catch(error => {
        console.error('Prompt optimization failed:', error);
      });
    }
  }, [data.inputPrompt, id, processNode, data.result, status]);

  return (
    <BaseNode
      id={id}
      title="提示词优化"
      inputs={inputs}
      outputs={outputs}
    >
      <div className="space-y-2">
        {data.inputPrompt && (
          <div className="text-xs text-gray-600">
            <div className="font-medium">输入:</div>
            <div className="bg-gray-50 p-2 rounded text-xs">
              {data.inputPrompt}
            </div>
          </div>
        )}
        
        {status === 'loading' && (
          <div className="text-xs text-blue-600 text-center">
            🤖 AI优化中... {Math.round(progress)}%
          </div>
        )}

        {data.result && status === 'success' && (
          <div className="text-xs text-gray-600">
            <div className="font-medium text-green-600">优化结果:</div>
            <div className="bg-green-50 p-2 rounded text-xs max-h-20 overflow-y-auto">
              {data.result}
            </div>
          </div>
        )}
      </div>
    </BaseNode>
  );
};
