import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import {
  RefreshCw,
  Server,
  FileText,
  CheckCircle,
  XCircle,
  AlertCircle,
  Clock,
  Database,
  Download,
  Play,
  Eye,
  Copy
} from 'lucide-react';

interface ComfyUISystemStats {
  system: {
    os: string;
    ram_total: number;
    ram_free: number;
    comfyui_version: string;
    python_version: string;
  };
}

interface ComfyUIQueue {
  queue_running: any[];
  queue_pending: any[];
}

interface ComfyUIHistory {
  [key: string]: {
    prompt: any;
    outputs: any;
    status: {
      status_str: string;
      completed: boolean;
      messages: any[];
    };
  };
}

interface WorkflowInfo {
  id: string;
  name: string;
  description: string;
  status: string;
  completed: boolean;
  node_count: number;
  created_at: string;
  prompt_data: any;
  outputs?: any;
}

export const ComfyUIWorkflowTest: React.FC = () => {
  const [connectionStatus, setConnectionStatus] = useState<'testing' | 'connected' | 'failed'>('testing');
  const [systemStats, setSystemStats] = useState<ComfyUISystemStats | null>(null);
  const [queue, setQueue] = useState<ComfyUIQueue | null>(null);
  const [history, setHistory] = useState<ComfyUIHistory | null>(null);
  const [workflows, setWorkflows] = useState<WorkflowInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedWorkflow, setSelectedWorkflow] = useState<WorkflowInfo | null>(null);

  // 测试连接
  const testConnection = async () => {
    setLoading(true);
    setError(null);
    setConnectionStatus('testing');

    try {
      // 注意：这里不更新全局 ComfyUI 配置，避免影响集群管理系统
      // 直接使用本地节点地址进行连接测试
      const nodeUrl = 'http://192.168.0.193:8188';

      console.log('🔗 直接测试本地节点连接...', nodeUrl);

      // 2. 直接测试节点连接
      try {
        const stats = await invoke<ComfyUISystemStats>('comfyui_node_get_data', {
          nodeUrl: nodeUrl,
          endpoint: 'system_stats'
        });
        console.log('✅ 节点连接成功:', stats);
        setConnectionStatus('connected');
        setSystemStats(stats);

        // 3. 获取其他系统信息
        await fetchSystemInfo();
      } catch (err) {
        console.error('❌ 节点连接失败:', err);
        setConnectionStatus('failed');
        setError('无法连接到 ComfyUI 节点: ' + (err instanceof Error ? err.message : '未知错误'));
      }
    } catch (err) {
      console.error('连接测试失败:', err);
      setConnectionStatus('failed');
      setError(err instanceof Error ? err.message : '连接测试失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取系统信息
  const fetchSystemInfo = async () => {
    const nodeUrl = 'http://192.168.0.193:8188';

    try {
      // 获取队列状态
      try {
        const queueData = await invoke<ComfyUIQueue>('comfyui_node_get_data', {
          nodeUrl: nodeUrl,
          endpoint: 'queue'
        });
        setQueue(queueData);
        console.log('📋 队列状态:', queueData);
      } catch (err) {
        console.error('获取队列状态失败:', err);
      }

    } catch (err) {
      console.error('获取系统信息失败:', err);
      setError('获取系统信息失败');
    }
  };

  // 尝试获取工作流列表
  const fetchWorkflows = async () => {
    setLoading(true);
    setError(null);
    const nodeUrl = 'http://192.168.0.193:8188';

    try {
      // 直接从 ComfyUI 节点历史记录中获取工作流信息
      const historyData = await invoke<ComfyUIHistory>('comfyui_node_get_data', {
        nodeUrl: nodeUrl,
        endpoint: 'history'
      });
      console.log('📂 获取到历史记录:', historyData);

      const workflowsFromHistory = extractWorkflowsFromHistory(historyData);
      setWorkflows(workflowsFromHistory);
      setHistory(historyData);

      console.log('📂 提取到工作流:', workflowsFromHistory);
    } catch (err) {
      console.error('获取工作流失败:', err);
      setError('获取工作流失败: ' + (err instanceof Error ? err.message : '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 从历史记录中提取工作流信息
  const extractWorkflowsFromHistory = (historyData: ComfyUIHistory): WorkflowInfo[] => {
    const workflows: WorkflowInfo[] = [];

    console.log('🔍 开始提取工作流，历史记录条目数:', Object.keys(historyData).length);

    Object.entries(historyData).forEach(([id, record]) => {
      console.log(`🔍 处理记录 ${id}:`, {
        hasPrompt: !!record.prompt,
        promptLength: record.prompt?.length,
        status: record.status?.status_str,
        completed: record.status?.completed
      });

      if (record.prompt && Array.isArray(record.prompt) && record.prompt.length > 2 && record.prompt[2]) {
        const promptData = record.prompt[2];
        const nodeCount = Object.keys(promptData).length;

        workflows.push({
          id,
          name: `工作流 ${id.substring(0, 8)}`,
          description: `包含 ${nodeCount} 个节点`,
          status: record.status?.status_str || 'unknown',
          completed: record.status?.completed || false,
          node_count: nodeCount,
          created_at: new Date().toISOString(), // ComfyUI 不提供创建时间
          prompt_data: promptData,
          outputs: record.outputs
        });

        console.log(`✅ 成功提取工作流 ${id}, 节点数: ${nodeCount}`);
      } else {
        console.log(`⚠️ 跳过记录 ${id}: 无效的 prompt 数据`);
      }
    });

    console.log(`🎯 总共提取到 ${workflows.length} 个工作流`);
    return workflows.sort((a, b) => b.id.localeCompare(a.id)); // 按 ID 倒序排列
  };

  // 下载工作流为 JSON 文件
  const downloadWorkflow = (workflow: WorkflowInfo) => {
    const dataStr = JSON.stringify(workflow.prompt_data, 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 = `${workflow.name.replace(/\s+/g, '_')}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  // 复制工作流到剪贴板
  const copyWorkflowToClipboard = async (workflow: WorkflowInfo) => {
    try {
      await navigator.clipboard.writeText(JSON.stringify(workflow.prompt_data, null, 2));
      alert('工作流已复制到剪贴板！');
    } catch (err) {
      console.error('复制失败:', err);
      alert('复制失败，请手动复制');
    }
  };

  // 查看工作流详情
  const viewWorkflowDetails = (workflow: WorkflowInfo) => {
    setSelectedWorkflow(workflow);
  };

  // 初始化
  useEffect(() => {
    testConnection();
  }, []);

  const formatBytes = (bytes: number) => {
    const gb = bytes / (1024 * 1024 * 1024);
    return `${gb.toFixed(2)} GB`;
  };

  return (
    <div className="p-6 max-w-6xl mx-auto">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">ComfyUI 节点管理</h1>
        <p className="text-gray-600">
          直接连接到本地 ComfyUI 节点 (192.168.0.193:8188) 并管理工作流
        </p>
        <div className="mt-2 p-3 bg-blue-50 border border-blue-200 rounded-lg">
          <p className="text-sm text-blue-700">
            <strong>注意：</strong> 这是单节点管理系统，独立于 ComfyUI 集群管理。
            用于直接操作和监控单个 ComfyUI 实例。
          </p>
        </div>
      </div>

      {/* 连接状态 */}
      <div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-gray-900">连接状态</h2>
          <button
            onClick={testConnection}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            重新测试
          </button>
        </div>

        <div className="flex items-center gap-3">
          {connectionStatus === 'testing' && (
            <>
              <Clock className="w-5 h-5 text-yellow-500" />
              <span className="text-yellow-700">正在测试连接...</span>
            </>
          )}
          {connectionStatus === 'connected' && (
            <>
              <CheckCircle className="w-5 h-5 text-green-500" />
              <span className="text-green-700">连接成功</span>
            </>
          )}
          {connectionStatus === 'failed' && (
            <>
              <XCircle className="w-5 h-5 text-red-500" />
              <span className="text-red-700">连接失败</span>
            </>
          )}
        </div>

        {error && (
          <div className="mt-3 p-3 bg-red-50 border border-red-200 rounded-lg">
            <div className="flex items-center gap-2">
              <AlertCircle className="w-4 h-4 text-red-500" />
              <span className="text-red-700">{error}</span>
            </div>
          </div>
        )}
      </div>

      {/* 系统信息 */}
      {systemStats && (
        <div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <Server className="w-5 h-5" />
            系统信息
          </h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div>
              <div className="text-sm text-gray-500">操作系统</div>
              <div className="font-medium">{systemStats.system.os}</div>
            </div>
            <div>
              <div className="text-sm text-gray-500">ComfyUI 版本</div>
              <div className="font-medium">{systemStats.system.comfyui_version}</div>
            </div>
            <div>
              <div className="text-sm text-gray-500">总内存</div>
              <div className="font-medium">{formatBytes(systemStats.system.ram_total)}</div>
            </div>
            <div>
              <div className="text-sm text-gray-500">可用内存</div>
              <div className="font-medium">{formatBytes(systemStats.system.ram_free)}</div>
            </div>
          </div>
        </div>
      )}

      {/* 队列状态 */}
      {queue && (
        <div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">队列状态</h2>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <div className="text-sm text-gray-500">运行中</div>
              <div className="text-2xl font-bold text-blue-600">{queue.queue_running.length}</div>
            </div>
            <div>
              <div className="text-sm text-gray-500">等待中</div>
              <div className="text-2xl font-bold text-yellow-600">{queue.queue_pending.length}</div>
            </div>
          </div>
        </div>
      )}

      {/* 工作流列表 */}
      <div className="bg-white rounded-lg shadow-sm border p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
            <FileText className="w-5 h-5" />
            工作流列表
          </h2>
          <button
            onClick={fetchWorkflows}
            disabled={loading || connectionStatus !== 'connected'}
            className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
          >
            <Database className="w-4 h-4" />
            获取工作流
          </button>
        </div>

        {workflows.length > 0 ? (
          <div className="space-y-3">
            {workflows.map((workflow, index) => (
              <div key={workflow.id || index} className="border rounded-lg p-4 hover:shadow-md transition-shadow">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="font-medium text-gray-900">{workflow.name}</h3>
                  <div className="flex items-center gap-2">
                    <span className={`px-2 py-1 rounded-full text-xs ${
                      workflow.completed
                        ? 'bg-green-100 text-green-700'
                        : workflow.status === 'error'
                        ? 'bg-red-100 text-red-700'
                        : 'bg-yellow-100 text-yellow-700'
                    }`}>
                      {workflow.status}
                    </span>
                  </div>
                </div>
                <p className="text-sm text-gray-600 mb-3">{workflow.description}</p>
                <div className="text-xs text-gray-500 mb-3">
                  ID: {workflow.id.substring(0, 16)}...
                  {workflow.node_count && ` • 节点数: ${workflow.node_count}`}
                </div>

                {/* 操作按钮 */}
                <div className="flex items-center gap-2 pt-2 border-t">
                  <button
                    onClick={() => viewWorkflowDetails(workflow)}
                    className="flex items-center gap-1 px-3 py-1 text-xs bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors"
                  >
                    <Eye className="w-3 h-3" />
                    查看详情
                  </button>
                  <button
                    onClick={() => downloadWorkflow(workflow)}
                    className="flex items-center gap-1 px-3 py-1 text-xs bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors"
                  >
                    <Download className="w-3 h-3" />
                    下载
                  </button>
                  <button
                    onClick={() => copyWorkflowToClipboard(workflow)}
                    className="flex items-center gap-1 px-3 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
                  >
                    <Copy className="w-3 h-3" />
                    复制
                  </button>
                  {workflow.completed && (
                    <button
                      onClick={() => {/* TODO: 实现重新执行功能 */}}
                      className="flex items-center gap-1 px-3 py-1 text-xs bg-purple-100 text-purple-700 rounded hover:bg-purple-200 transition-colors"
                    >
                      <Play className="w-3 h-3" />
                      重新执行
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-8 text-gray-500">
            {connectionStatus === 'connected'
              ? '暂无工作流数据，请点击"获取工作流"按钮'
              : '请先建立连接'}
          </div>
        )}
      </div>

      {/* 工作流详情模态框 */}
      {selectedWorkflow && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-4xl max-h-[80vh] w-full mx-4 overflow-hidden">
            <div className="flex items-center justify-between p-6 border-b">
              <h2 className="text-xl font-semibold text-gray-900">工作流详情</h2>
              <button
                onClick={() => setSelectedWorkflow(null)}
                className="text-gray-400 hover:text-gray-600"
              >
                <XCircle className="w-6 h-6" />
              </button>
            </div>

            <div className="p-6 overflow-y-auto max-h-[60vh]">
              <div className="grid grid-cols-2 gap-4 mb-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">工作流名称</label>
                  <div className="text-gray-900">{selectedWorkflow.name}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
                  <span className={`px-2 py-1 rounded-full text-xs ${
                    selectedWorkflow.completed
                      ? 'bg-green-100 text-green-700'
                      : selectedWorkflow.status === 'error'
                      ? 'bg-red-100 text-red-700'
                      : 'bg-yellow-100 text-yellow-700'
                  }`}>
                    {selectedWorkflow.status}
                  </span>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">工作流 ID</label>
                  <div className="text-gray-900 font-mono text-sm">{selectedWorkflow.id}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">节点数量</label>
                  <div className="text-gray-900">{selectedWorkflow.node_count}</div>
                </div>
              </div>

              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-2">工作流 JSON</label>
                <div className="bg-gray-50 rounded-lg p-4 max-h-96 overflow-y-auto">
                  <pre className="text-xs text-gray-800 whitespace-pre-wrap">
                    {JSON.stringify(selectedWorkflow.prompt_data, null, 2)}
                  </pre>
                </div>
              </div>

              {selectedWorkflow.outputs && (
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 mb-2">输出结果</label>
                  <div className="bg-gray-50 rounded-lg p-4 max-h-48 overflow-y-auto">
                    <pre className="text-xs text-gray-800 whitespace-pre-wrap">
                      {JSON.stringify(selectedWorkflow.outputs, null, 2)}
                    </pre>
                  </div>
                </div>
              )}
            </div>

            <div className="flex items-center justify-end gap-3 p-6 border-t bg-gray-50">
              <button
                onClick={() => copyWorkflowToClipboard(selectedWorkflow)}
                className="flex items-center gap-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700"
              >
                <Copy className="w-4 h-4" />
                复制 JSON
              </button>
              <button
                onClick={() => downloadWorkflow(selectedWorkflow)}
                className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                <Download className="w-4 h-4" />
                下载文件
              </button>
              <button
                onClick={() => setSelectedWorkflow(null)}
                className="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300"
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ComfyUIWorkflowTest;
