import { useState, useEffect, useCallback } from 'react';
import { TopBar } from './components/Layout/TopBar';
import { CollapsibleSidebar } from './components/Layout/CollapsibleSidebar';
import { SettingsLayout } from './components/Settings/SettingsLayout';
import { AgentLayout } from './components/Agent/AgentLayout';
import { PluginLayout } from './components/Plugin/PluginLayout';
import { LeftPanel } from './components/Chat/LeftPanel';
import { ChatPanel } from './components/Chat/ChatPanel';
import { RightPanel } from './components/Chat/RightPanel';
import { WorkflowListView } from './components/Chat/WorkflowListView';
import { NewWorkflowDialog } from './components/Chat/NewWorkflowDialog';
import { AuthPage } from './components/Auth/AuthPage';
import apiClient from './api/client';
import type { ChatSessionDB } from './types';

export interface Message {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: number;
}

export interface ChatSession {
  id: string;
  title: string;
  messages: Message[];
  updatedAt: number;
}

function mapSessionFromDB(s: ChatSessionDB): ChatSession {
  return {
    id: s.chat_id,
    title: s.title,
    messages: [],
    updatedAt: new Date(s.updated_at).getTime(),
  };
}

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  const [mode, setMode] = useState<'work' | 'agent'>('work');
  const [showSettings, setShowSettings] = useState(false);
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);

  const [workTab, setWorkTab] = useState<'chat' | 'workflow'>('chat');
  const [selectedWorkflow, setSelectedWorkflow] = useState<string | null>(null);

  const [agentTab, setAgentTab] = useState<'plugin' | 'agents'>('plugin');
  const [settingsTab, setSettingsTab] = useState('users');
  const [innerAgentTab, setInnerAgentTab] = useState('worker');
  const [resourceTab, setResourceTab] = useState('skill');

  const [chatSessions, setChatSessions] = useState<ChatSession[]>([]);
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null);

  const loadChatSessions = useCallback(async () => {
    try {
      const response = await apiClient.get('/api/v1/chat');
      const sessions: ChatSessionDB[] = response.data?.sessions || [];
      setChatSessions(sessions.map(mapSessionFromDB));
    } catch (error) {
      console.error('Failed to load chat sessions', error);
    }
  }, []);

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token) {
      setIsAuthenticated(true);
    }
  }, []);

  useEffect(() => {
    if (isAuthenticated) {
      loadChatSessions();
    }
  }, [isAuthenticated, loadChatSessions]);

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

  return (
    <div className="flex flex-col h-screen w-screen bg-slate-50 text-slate-800 font-sans overflow-hidden">
      <TopBar
        mode={mode}
        setMode={setMode}
        showSettings={showSettings}
        setShowSettings={setShowSettings}
      />

      <div className="flex flex-1 overflow-hidden relative">
        {showSettings ? (
          <SettingsLayout settingsTab={settingsTab} setSettingsTab={setSettingsTab} />
        ) : (
          <>
            <CollapsibleSidebar
              mode={mode}
              isOpen={isSidebarOpen}
              setIsOpen={setIsSidebarOpen}
              workTab={workTab}
              setWorkTab={setWorkTab}
              agentTab={agentTab}
              setAgentTab={setAgentTab}
            />

            <div className="flex-1 flex overflow-hidden">
              {mode === 'work' && workTab === 'chat' && (
                <div className="flex-1 p-6 flex overflow-hidden">
                  <div className="flex-1 flex bg-white rounded-3xl shadow-md border border-slate-200 overflow-hidden relative">
                    <LeftPanel
                      activeTab="chats"
                      selectedWorkflow={null}
                      setSelectedWorkflow={() => {}}
                      chatSessions={chatSessions}
                      setChatSessions={setChatSessions}
                      activeSessionId={activeSessionId}
                      setActiveSessionId={setActiveSessionId}
                      onSessionsChanged={loadChatSessions}
                    />
                    <ChatPanel
                      chatSessions={chatSessions}
                      setChatSessions={setChatSessions}
                      activeSessionId={activeSessionId}
                      setActiveSessionId={setActiveSessionId}
                      onSessionsChanged={loadChatSessions}
                    />
                  </div>
                </div>
              )}

              {mode === 'work' && workTab === 'workflow' && (
                <>
                  {selectedWorkflow === 'new' ? (
                    <>
                      <LeftPanel
                        activeTab="workflows"
                        selectedWorkflow={selectedWorkflow}
                        setSelectedWorkflow={setSelectedWorkflow}
                      />
                      <NewWorkflowDialog
                        onClose={() => setSelectedWorkflow(null)}
                        onSuccess={(traceId: string) => setSelectedWorkflow(traceId)}
                      />
                    </>
                  ) : selectedWorkflow ? (
                    <>
                      <LeftPanel
                        activeTab="workflows"
                        selectedWorkflow={selectedWorkflow}
                        setSelectedWorkflow={setSelectedWorkflow}
                      />
                      <RightPanel selectedWorkflow={selectedWorkflow} />
                    </>
                  ) : (
                    <WorkflowListView onSelectWorkflow={setSelectedWorkflow} />
                  )}
                </>
              )}

              {mode === 'agent' && agentTab === 'agents' && (
                <AgentLayout agentTab={innerAgentTab} setAgentTab={setInnerAgentTab} />
              )}

              {mode === 'agent' && agentTab === 'plugin' && (
                <PluginLayout resourceTab={resourceTab} setResourceTab={setResourceTab} />
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

export default App;
