/**
 * App Component
 *
 * 响应式布局：支持桌面端和移动端
 */

import { useState, useEffect, useCallback } from 'react';
import {
  Sidebar,
  FileBrowser,
  CommandPanel,
  MCPPanel,
  HooksPanel,
  AgentsPanel,
  CheckpointPanel,
  ProvidersPanel,
  Toaster,
  ThemeProvider,
  listSessions,
  createSession,
  getWorkingDirectory,
  type Session,
} from '@ai-assistant/ui';
import { ChatPage } from './pages/Chat';

export function App() {
  const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
  const [isInitializing, setIsInitializing] = useState(true);
  const [showFileBrowser, setShowFileBrowser] = useState(false);
  const [showCommands, setShowCommands] = useState(false);
  const [showMCP, setShowMCP] = useState(false);
  const [showHooks, setShowHooks] = useState(false);
  const [showAgents, setShowAgents] = useState(false);
  const [showCheckpoints, setShowCheckpoints] = useState(false);
  const [showProviders, setShowProviders] = useState(false);
  const [sessionTitleUpdate, setSessionTitleUpdate] = useState<{ sessionId: string; name: string } | null>(null);
  const [workingDirectory, setWorkingDirectory] = useState<string>('');

  // 初始化：加载会话和工作目录
  useEffect(() => {
    const HAS_SESSIONS_KEY = 'ai-assistant-has-sessions';

    async function init() {
      try {
        // 并行获取会话和工作目录
        const [sessionsResult, workdirResult] = await Promise.all([
          listSessions(),
          getWorkingDirectory().catch(() => null),
        ]);

        const { data: sessions } = sessionsResult;

        // 设置工作目录
        if (workdirResult?.data?.workingDirectory) {
          setWorkingDirectory(workdirResult.data.workingDirectory);
        }

        if (sessions.length > 0) {
          // 有会话，选择最近的
          setCurrentSessionId(sessions[0].id);
          localStorage.setItem(HAS_SESSIONS_KEY, 'true');
        } else {
          // 无会话：检查是否是首次启动
          const hasHadSessions = localStorage.getItem(HAS_SESSIONS_KEY);

          if (!hasHadSessions) {
            // 首次启动，自动创建会话
            const { data: newSession } = await createSession();
            setCurrentSessionId(newSession.id);
            localStorage.setItem(HAS_SESSIONS_KEY, 'true');
          }
          // 用户删除了所有会话：不自动创建，显示空状态
        }
      } catch (error) {
        console.error('Failed to initialize:', error);
      } finally {
        setIsInitializing(false);
      }
    }

    init();
  }, []);

  const handleSelectSession = (id: string) => {
    setCurrentSessionId(id);
  };

  const handleCreateSession = (session: Session) => {
    setCurrentSessionId(session.id);
  };

  // 会话不存在时自动创建新会话
  const handleSessionNotFound = useCallback(async () => {
    try {
      const { data: newSession } = await createSession();
      setCurrentSessionId(newSession.id);
    } catch (error) {
      console.error('Failed to create new session:', error);
    }
  }, []);

  // 会话标题更新回调
  const handleSessionUpdated = useCallback((sessionId: string, name: string) => {
    setSessionTitleUpdate({ sessionId, name });
  }, []);

  if (isInitializing) {
    return (
      <ThemeProvider>
        <div className="h-screen flex items-center justify-center bg-surface-base">
          <div className="text-center">
            <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
            <p className="text-fg-muted">Initializing...</p>
          </div>
        </div>
      </ThemeProvider>
    );
  }

  return (
    <ThemeProvider>
      <div className="h-screen flex bg-surface-base">
        <Sidebar
          currentSessionId={currentSessionId}
          onSelectSession={handleSelectSession}
          onCreateSession={handleCreateSession}
          responsive
          sessionTitleUpdate={sessionTitleUpdate}
        />

        {/* 主内容区域 */}
        <div className="flex-1 flex min-w-0">
          {/* 聊天区域 */}
          <div className={`flex-1 min-w-0 ${showFileBrowser ? 'hidden md:block md:w-1/2' : 'w-full'}`}>
            {currentSessionId ? (
              <ChatPage
                key={currentSessionId}
                sessionId={currentSessionId}
                onSessionNotFound={handleSessionNotFound}
                onSessionUpdated={handleSessionUpdated}
                responsive
                showFileBrowser={showFileBrowser}
                onToggleFileBrowser={() => setShowFileBrowser(!showFileBrowser)}
                onOpenCommands={() => setShowCommands(true)}
                onOpenMCP={() => setShowMCP(true)}
                onOpenHooks={() => setShowHooks(true)}
                onOpenAgents={() => setShowAgents(true)}
                onOpenCheckpoints={() => setShowCheckpoints(true)}
                onOpenProviders={() => setShowProviders(true)}
                workingDirectory={workingDirectory}
              />
            ) : (
              <div className="flex-1 flex items-center justify-center h-full">
                <p className="text-fg-muted">Select or create a session</p>
              </div>
            )}
          </div>

          {/* 文件浏览器 - 桌面端侧边栏，移动端全屏覆盖 */}
          {showFileBrowser && (
            <>
              {/* 移动端: 全屏覆盖 */}
              <div className="fixed inset-0 z-50 bg-surface-base md:hidden">
                <div className="flex items-center justify-between p-3 border-b border-line">
                  <span className="text-lg font-semibold text-fg">Files</span>
                  <button
                    onClick={() => setShowFileBrowser(false)}
                    className="p-2 rounded-lg bg-surface-muted text-fg-muted hover:bg-surface-emphasis"
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </div>
                <div className="h-[calc(100%-56px)]">
                  <FileBrowser
                    onFileSelect={(path, _content) => {
                      console.log('Selected file:', path);
                    }}
                  />
                </div>
              </div>

              {/* 桌面端: 侧边栏 */}
              <div className="hidden md:block w-1/2 border-l border-line">
                <FileBrowser
                  onFileSelect={(path, _content) => {
                    console.log('Selected file:', path);
                  }}
                />
              </div>
            </>
          )}
        </div>

        {/* 命令面板 */}
        {showCommands && <CommandPanel onClose={() => setShowCommands(false)} responsive />}

        {/* MCP 面板 */}
        {showMCP && <MCPPanel onClose={() => setShowMCP(false)} responsive />}

        {/* Hooks 面板 */}
        {showHooks && <HooksPanel onClose={() => setShowHooks(false)} responsive />}

        {/* Agents 面板 */}
        {showAgents && <AgentsPanel onClose={() => setShowAgents(false)} responsive />}

        {/* Checkpoints 面板 */}
        {showCheckpoints && <CheckpointPanel onClose={() => setShowCheckpoints(false)} responsive />}

        {/* Providers 面板 */}
        {showProviders && <ProvidersPanel onClose={() => setShowProviders(false)} responsive />}

        {/* 移动端底部文件按钮 */}
        <button
          onClick={() => setShowFileBrowser(true)}
          className="fixed bottom-20 right-4 z-30 p-3 rounded-full bg-surface-muted text-fg-muted hover:bg-surface-emphasis active:bg-surface-emphasis shadow-lg md:hidden"
          title="Browse Files"
        >
          <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"
            />
          </svg>
        </button>

        {/* Toast 通知 */}
        <Toaster />
      </div>
    </ThemeProvider>
  );
}
