import React, { useState, useEffect } from 'react';
import { ReactFlowProvider } from 'reactflow';
import { CanvasContainer } from '../components/canvas/CanvasContainer';
import { CanvasToolbar } from '../components/canvas/CanvasToolbar';
import { QuickStartTemplates } from '../components/canvas/QuickStartTemplates';
import { useCanvasStore } from '../store/canvasStore';

const CanvasTool: React.FC = () => {
  const [showQuickStart, setShowQuickStart] = useState(true);
  const { nodes, edges, setNodes, setEdges } = useCanvasStore();

  const handleSave = () => {
    try {
      const canvasData = {
        nodes,
        edges,
        timestamp: new Date().toISOString(),
        version: '1.0'
      };

      const dataStr = JSON.stringify(canvasData, null, 2);
      const dataBlob = new Blob([dataStr], { type: 'application/json' });
      const url = URL.createObjectURL(dataBlob);

      const link = document.createElement('a');
      link.href = url;
      link.download = `ai-canvas-${Date.now()}.json`;
      link.click();

      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('保存失败:', error);
      alert('保存失败，请重试');
    }
  };

  const handleLoad = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (event) => {
          try {
            const canvasData = JSON.parse(event.target?.result as string);

            // 验证数据格式
            if (canvasData.nodes && canvasData.edges) {
              setNodes(canvasData.nodes);
              setEdges(canvasData.edges);
              console.log('画布加载成功');
            } else {
              throw new Error('无效的画布文件格式');
            }
          } catch (error) {
            console.error('加载失败:', error);
            alert('加载失败，请检查文件格式');
          }
        };
        reader.readAsText(file);
      }
    };
    input.click();
  };

  const handleExport = () => {
    try {
      // 收集所有节点的结果
      const results = nodes
        .filter(node => node.data?.result)
        .map(node => ({
          id: node.id,
          type: node.type,
          result: node.data.result,
          position: node.position
        }));

      if (results.length === 0) {
        alert('没有可导出的结果');
        return;
      }

      const exportData = {
        results,
        exportTime: new Date().toISOString(),
        totalNodes: nodes.length,
        completedNodes: results.length
      };

      const dataStr = JSON.stringify(exportData, null, 2);
      const dataBlob = new Blob([dataStr], { type: 'application/json' });
      const url = URL.createObjectURL(dataBlob);

      const link = document.createElement('a');
      link.href = url;
      link.download = `ai-canvas-results-${Date.now()}.json`;
      link.click();

      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出失败:', error);
      alert('导出失败，请重试');
    }
  };

  return (
    <ReactFlowProvider>
      <div className="fixed inset-0 flex flex-col bg-gray-50 z-10">
        {/* 工具栏 */}
        <CanvasToolbar
          onSave={handleSave}
          onLoad={handleLoad}
          onExport={handleExport}
        />

        {/* 主画布区域 */}
        <div className="flex-1 relative overflow-hidden">
          <CanvasContainer />

          {/* 快速开始模板 */}
          {showQuickStart && nodes.length === 0 && (
            <QuickStartTemplates onClose={() => setShowQuickStart(false)} />
          )}
        </div>

      {/* 使用说明 */}
      <div className="absolute bottom-4 left-4 bg-white/90 backdrop-blur-sm rounded-lg p-3 shadow-lg border border-gray-200 max-w-sm">
        <h3 className="text-sm font-semibold text-gray-800 mb-2">使用说明</h3>
        <ul className="text-xs text-gray-600 space-y-1">
          <li>• 双击空白处创建节点</li>
          <li>• 拖拽端口连线建立数据流</li>
          <li>• 连线完成自动触发处理</li>
          <li>• 文件夹输入支持批量处理</li>
          <li>• 每个节点独立处理，互不阻塞</li>
        </ul>
      </div>
      </div>
    </ReactFlowProvider>
  );
};

export default CanvasTool;
