import React, { useState } from 'react';
import { useCanvasStore } from '../../store/canvasStore';
import { Save, FolderOpen, Download, Trash2, RotateCcw, Settings, ZoomIn } from 'lucide-react';
import { AIConfigModal } from './AIConfigModal';
import { AIServiceConfig, loadAIConfig } from '../../services/aiServices';
import { useReactFlow } from 'reactflow';

interface CanvasToolbarProps {
  onSave?: () => void;
  onLoad?: () => void;
  onExport?: () => void;
}

export const CanvasToolbar: React.FC<CanvasToolbarProps> = ({
  onSave,
  onLoad,
  onExport
}) => {
  const [showAIConfig, setShowAIConfig] = useState(false);
  const [aiConfig, setAiConfig] = useState<AIServiceConfig>(loadAIConfig());
  const { fitView } = useReactFlow();

  const {
    nodes,
    edges,
    clearCanvas,
    resetCanvas,
    processingNodes
  } = useCanvasStore();

  const handleSave = () => {
    if (onSave) {
      onSave();
    } else {
      // 默认保存逻辑
      const canvasData = {
        nodes,
        edges,
        timestamp: new Date().toISOString()
      };
      
      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 = `canvas-${Date.now()}.json`;
      link.click();
      
      URL.revokeObjectURL(url);
    }
  };

  const handleLoad = () => {
    if (onLoad) {
      onLoad();
    } else {
      // 默认加载逻辑
      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);
              // TODO: 实现加载逻辑
              console.log('加载画布数据:', canvasData);
            } catch (error) {
              console.error('加载失败:', error);
            }
          };
          reader.readAsText(file);
        }
      };
      input.click();
    }
  };

  const handleExport = () => {
    if (onExport) {
      onExport();
    } else {
      // 默认导出逻辑
      console.log('导出画布');
    }
  };

  const handleClear = () => {
    if (confirm('确定要清空画布吗？此操作不可撤销。')) {
      clearCanvas();
    }
  };

  const handleReset = () => {
    if (confirm('确定要重置画布吗？这将清空所有内容并重置视图。')) {
      resetCanvas();
    }
  };

  const handleAIConfigSave = (newConfig: AIServiceConfig) => {
    setAiConfig(newConfig);
    // 保存到本地存储
    localStorage.setItem('aiConfig', JSON.stringify(newConfig));
  };

  const handleFitView = () => {
    fitView({
      padding: 0.1,
      includeHiddenNodes: false,
      minZoom: 0.1,
      maxZoom: 2
    });
  };

  const activeProcessingCount = processingNodes.size;
  const hasNodes = nodes.length > 0;

  return (
    <div className="h-12 bg-white border-b border-gray-200 flex items-center justify-between px-4 flex-shrink-0">
      {/* 左侧：标题和说明 */}
      <div className="flex items-center space-x-4">
        <div className="flex items-center space-x-2">
          <div className="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
            <span className="text-white font-bold text-sm">AI</span>
          </div>
          <h1 className="text-lg font-semibold text-gray-800">AI画布工具</h1>
        </div>
        
        <div className="text-sm text-gray-500 hidden md:block">
          双击空白处创建节点，拖拽连线建立数据流
        </div>

        {/* 状态指示器 */}
        {activeProcessingCount > 0 && (
          <div className="flex items-center space-x-1 text-sm text-blue-600 bg-blue-50 px-2 py-1 rounded">
            <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse" />
            <span>{activeProcessingCount} 个节点处理中</span>
          </div>
        )}
      </div>
      
      {/* 右侧：操作按钮 */}
      <div className="flex items-center space-x-2">
        {/* 文件操作 */}
        <div className="flex items-center space-x-1">
          <button
            onClick={handleSave}
            disabled={!hasNodes}
            className="flex items-center space-x-1 px-3 py-1.5 text-sm bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            title="保存画布"
          >
            <Save size={16} />
            <span className="hidden sm:inline">保存</span>
          </button>
          
          <button
            onClick={handleLoad}
            className="flex items-center space-x-1 px-3 py-1.5 text-sm bg-gray-500 text-white rounded-md hover:bg-gray-600 transition-colors"
            title="加载画布"
          >
            <FolderOpen size={16} />
            <span className="hidden sm:inline">加载</span>
          </button>
          
          <button
            onClick={handleExport}
            disabled={!hasNodes}
            className="flex items-center space-x-1 px-3 py-1.5 text-sm bg-green-500 text-white rounded-md hover:bg-green-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            title="导出结果"
          >
            <Download size={16} />
            <span className="hidden sm:inline">导出</span>
          </button>
        </div>
        
        <div className="w-px h-6 bg-gray-300 mx-2" />

        {/* AI 配置 */}
        <button
          onClick={() => setShowAIConfig(true)}
          className="flex items-center space-x-1 px-3 py-1.5 text-sm bg-purple-500 text-white rounded-md hover:bg-purple-600 transition-colors"
          title="AI服务配置"
        >
          <Settings size={16} />
          <span className="hidden sm:inline">配置</span>
        </button>

        <div className="w-px h-6 bg-gray-300 mx-2" />

        {/* 画布操作 */}
        <div className="flex items-center space-x-1">
          <button
            onClick={handleFitView}
            disabled={!hasNodes}
            className="flex items-center space-x-1 px-3 py-1.5 text-sm bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            title="适应视图"
          >
            <ZoomIn size={16} />
            <span className="hidden sm:inline">适应</span>
          </button>

          <button
            onClick={handleReset}
            disabled={!hasNodes}
            className="flex items-center space-x-1 px-3 py-1.5 text-sm bg-yellow-500 text-white rounded-md hover:bg-yellow-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            title="重置画布"
          >
            <RotateCcw size={16} />
            <span className="hidden sm:inline">重置</span>
          </button>
          
          <button
            onClick={handleClear}
            disabled={!hasNodes}
            className="flex items-center space-x-1 px-3 py-1.5 text-sm bg-red-500 text-white rounded-md hover:bg-red-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            title="清空画布"
          >
            <Trash2 size={16} />
            <span className="hidden sm:inline">清空</span>
          </button>
        </div>
      </div>

      {/* AI 配置模态框 */}
      <AIConfigModal
        isOpen={showAIConfig}
        onClose={() => setShowAIConfig(false)}
        onSave={handleAIConfigSave}
        currentConfig={aiConfig}
      />
    </div>
  );
};
