import { useState, useEffect } from 'react';
import { Sidebar } from './components/Layout/Sidebar';
import { SettingsLayout } from './components/Settings/SettingsLayout';
import { AgentLayout } from './components/Agent/AgentLayout';
import { ResourceLayout } from './components/Resource/ResourceLayout';
import { LeftPanel } from './components/Chat/LeftPanel';
import { ChatPanel } from './components/Chat/ChatPanel';
import { RightPanel } from './components/Chat/RightPanel';
import { AuthPage } from './components/Auth/AuthPage';

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [activeTab, setActiveTab] = useState('chats'); // For LeftPanel
  const [currentView, setCurrentView] = useState('dashboard'); // 'dashboard', 'settings', 'agent', 'resource'
  const [settingsTab, setSettingsTab] = useState('users'); // For SettingsLayout
  const [agentTab, setAgentTab] = useState('worker'); // For AgentLayout
  const [resourceTab, setResourceTab] = useState('skill'); // For ResourceLayout

  const [selectedWorkflow, setSelectedWorkflow] = useState<string | null>(null);

  useEffect(() => {
    // Check if token exists in localStorage on mount
    const token = localStorage.getItem('token');
    if (token) {
      setIsAuthenticated(true);
    }
  }, []);

  if (!isAuthenticated) {
    return <AuthPage onLoginSuccess={() => setIsAuthenticated(true)} />;
  }

  return (
    <div className="flex h-screen w-screen bg-slate-50 text-slate-800 font-sans overflow-hidden">

      {/* 1. Sidebar (Leftmost) */}
      <Sidebar currentView={currentView} setCurrentView={setCurrentView} />

      {/* Main Content Area depending on view */}
      {currentView === 'agent' ? (
        <AgentLayout agentTab={agentTab} setAgentTab={setAgentTab} />
      ) : currentView === 'resource' ? (
        <ResourceLayout resourceTab={resourceTab} setResourceTab={setResourceTab} />
      ) : currentView === 'dashboard' ? (
        <>
          {/* 2. Left Panel - Cluster Status & Workflows/Chats */}
          <LeftPanel
            activeTab={activeTab}
            setActiveTab={setActiveTab}
            selectedWorkflow={selectedWorkflow}
            setSelectedWorkflow={setSelectedWorkflow}
          />

          {/* 3. Middle Panel - AI Chat */}
          <ChatPanel />

          {/* 4. Right Panel - Workflow Execution Status (Only show when viewing workflows) */}
          {activeTab === 'workflows' && <RightPanel selectedWorkflow={selectedWorkflow} />}
        </>
      ) : (
        /* Settings View */
        <SettingsLayout settingsTab={settingsTab} setSettingsTab={setSettingsTab} />
      )}

    </div>
  );
}

export default App;
