/**
 * ComfyUI V2 仪表板页面
 * 现代化的主界面，集成所有功能模块
 */

import React, { useEffect } from 'react';
import { 
  Squares2X2Icon,
  RectangleStackIcon,
  PlayIcon,
  ChartBarIcon,
  Cog6ToothIcon,
} from '@heroicons/react/24/outline';
import { useComfyUIV2Store } from '../store/comfyuiV2Store';
import { ComfyUIConnectionPanel } from '../components/comfyui/ComfyUIConnectionPanel';
import { WorkflowManager } from '../components/comfyui/WorkflowManager';
import { ExecutionMonitor } from '../components/comfyui/ExecutionMonitor';
import { RealtimeEventListener } from '../components/comfyui/RealtimeEventListener';
import { QueueStatusMonitor } from '../components/comfyui/QueueStatusMonitor';
import { Card, CardContent, CardHeader, CardTitle } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { ToastContainer, useToast } from '../components/ui/Toast';

type TabType = 'overview' | 'workflows' | 'executions' | 'monitoring' | 'settings';

export const ComfyUIV2Dashboard: React.FC = () => {
  const { isConnected, connectionStatus, systemInfo, queueStatus } = useComfyUIV2Store();
  const { toasts, toast } = useToast();
  const [activeTab, setActiveTab] = React.useState<TabType>('overview');

  // 连接状态变化时显示通知
  useEffect(() => {
    if (connectionStatus) {
      if (connectionStatus.connected && !isConnected) {
        toast.success('连接成功', 'ComfyUI 服务连接成功');
      } else if (!connectionStatus.connected && isConnected) {
        toast.error('连接断开', 'ComfyUI 服务连接已断开');
      }
    }
  }, [connectionStatus?.connected, isConnected]); // 移除 toast 依赖

  const tabs = [
    {
      id: 'overview' as TabType,
      name: '概览',
      icon: Squares2X2Icon,
      description: '系统状态和快速操作',
    },
    {
      id: 'workflows' as TabType,
      name: '工作流',
      icon: RectangleStackIcon,
      description: '管理和执行工作流',
    }
  ];

  const renderTabContent = () => {
    switch (activeTab) {
      case 'overview':
        return <OverviewTab />;
      case 'workflows':
        return <WorkflowsTab />;
      case 'executions':
        return <ExecutionsTab />;
      case 'monitoring':
        return <MonitoringTab />;
      case 'settings':
        return <SettingsTab />;
      default:
        return <OverviewTab />;
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 头部导航 */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-40">
        <div className="px-6 py-4">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">ComfyUI V2</h1>
              <p className="text-sm text-gray-500 mt-1">现代化 AI 工作流管理平台</p>
            </div>
            
            <div className="flex items-center space-x-4">
              {/* 连接状态指示器 */}
              <div className="flex items-center space-x-2">
                <div className={`w-3 h-3 rounded-full ${
                  isConnected ? 'bg-green-500' : 'bg-red-500'
                }`} />
                <span className="text-sm text-gray-600">
                  {isConnected ? '已连接' : '未连接'}
                </span>
              </div>
              
              {/* 系统信息 */}
              {systemInfo && (
                <div className="text-sm text-gray-500">
                  v{systemInfo.version}
                </div>
              )}
            </div>
          </div>
        </div>
        
        {/* 标签导航 */}
        <nav className="px-6">
          <div className="flex space-x-8">
            {tabs.map((tab) => {
              const Icon = tab.icon;
              const isActive = activeTab === tab.id;
              
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`flex items-center space-x-2 py-4 border-b-2 transition-colors ${
                    isActive
                      ? 'border-blue-500 text-blue-600'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  }`}
                >
                  <Icon className="w-5 h-5" />
                  <span className="font-medium">{tab.name}</span>
                </button>
              );
            })}
          </div>
        </nav>
      </header>

      {/* 主内容区域 */}
      <main className="p-6">
        {renderTabContent()}
      </main>

      {/* 通知容器 */}
      <ToastContainer toasts={toasts} position="top-right" />
    </div>
  );
};

// 概览标签页
const OverviewTab: React.FC = () => {
  const { isConnected, queueStatus, systemInfo } = useComfyUIV2Store();

  return (
    <div className="space-y-6">
      {/* 连接面板 */}
      <ComfyUIConnectionPanel />
      
      {isConnected && (
        <>
          {/* 状态卡片 */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-600">运行中任务</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-blue-600">
                  {queueStatus?.running_count || 0}
                </div>
              </CardContent>
            </Card>
            
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-600">等待中任务</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-yellow-600">
                  {queueStatus?.pending_count || 0}
                </div>
              </CardContent>
            </Card>
            
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-600">历史记录</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-green-600">
                  {queueStatus?.history_count || 0}
                </div>
              </CardContent>
            </Card>
            
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-600">系统版本</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-lg font-semibold text-gray-900">
                  {systemInfo?.version || 'N/A'}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 队列状态和实时事件 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <QueueStatusMonitor showChart />
            <RealtimeEventListener showEventLog />
          </div>
        </>
      )}
    </div>
  );
};

// 工作流标签页
const WorkflowsTab: React.FC = () => {
  return (
    <div className="space-y-6">
      <WorkflowManager />
    </div>
  );
};

// 执行记录标签页
const ExecutionsTab: React.FC = () => {
  return (
    <div className="space-y-6">
      <ExecutionMonitor showCompleted maxItems={20} />
    </div>
  );
};

// 监控标签页
const MonitoringTab: React.FC = () => {
  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <QueueStatusMonitor showChart />
        <RealtimeEventListener showEventLog maxEvents={50} />
      </div>
      
      <Card>
        <CardHeader>
          <CardTitle>性能监控</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8 text-gray-500">
            性能监控功能开发中...
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

// 设置标签页
const SettingsTab: React.FC = () => {
  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>系统设置</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8 text-gray-500">
            设置功能开发中...
          </div>
        </CardContent>
      </Card>
    </div>
  );
};
