import { useEffect, useState } from 'react';
import { VigthoriaLogo } from '@/components/VigthoriaLogo';
import { AgentPromptBar } from '@/features/agent/AgentPromptBar';
import { AgentStatusBar } from '@/features/agent/AgentStatusBar';
import { AuthGate } from '@/features/agent/AuthGate';
import { ServicesPanel } from '@/features/services/ServicesPanel';
import { SettingsModal } from '@/features/settings/SettingsModal';
import { PaneGrid } from '@/features/workspace/PaneGrid';
import { Sidebar } from '@/features/workspace/Sidebar';
import { V4SubAgentCanvas } from '@/features/workspace/V4SubAgentCanvas';
import { isPlaceholderRoot } from '@/lib/workspace-path';
import { useActiveWorkspace, useWorkbenchStore } from '@/features/workspace/WorkspaceStore';

function roleLabel(role: string): string {
  switch (role) {
    case 'mainAgent': return 'Main Agent';
    case 'dev': return 'Dev';
    case 'shell': return 'Shell';
    case 'git': return 'Git';
    case 'logs': return 'Logs';
    case 'bridge': return 'Bridge';
    default: return role;
  }
}

export function WorkspaceShell() {
  const workspace = useActiveWorkspace();
  const activeSessions = useWorkbenchStore((s) => s.activeSessions);
  const loading = useWorkbenchStore((s) => s.loading);
  const terminalEpoch = useWorkbenchStore((s) => s.terminalEpoch);
  const showTools = useWorkbenchStore((s) => s.settings.showReportPanel);
  const rootReady = workspace ? !isPlaceholderRoot(workspace.rootPath) : false;
  const v4SubAgents = useWorkbenchStore((s) => s.v4SubAgents);
  const appVersion = useWorkbenchStore((s) => s.appVersion);
  const updateAvailable = useWorkbenchStore((s) => s.updateInfo?.updateAvailable ?? false);
  const setSettingsOpen = useWorkbenchStore((s) => s.setSettingsOpen);
  const [activeV4AgentId, setActiveV4AgentId] = useState<string>('');
  const [v4Collapsed, setV4Collapsed] = useState(false);
  const [v4View, setV4View] = useState<'canvas' | 'list'>('canvas');

  useEffect(() => {
    if (v4SubAgents.length === 0) {
      if (activeV4AgentId) setActiveV4AgentId('');
      return;
    }
    if (!v4SubAgents.some((agent) => agent.agentId === activeV4AgentId)) {
      setActiveV4AgentId(v4SubAgents[0].agentId);
    }
  }, [activeV4AgentId, v4SubAgents]);

  const activeV4Agent = v4SubAgents.find((agent) => agent.agentId === activeV4AgentId) ?? v4SubAgents[0];

  if (loading) {
    return <div className="app-loading">Loading Vigthoria Workbench…</div>;
  }

  return (
    <div className="workspace-shell">
      <Sidebar />
      <main className="workspace-main">
        <header className="workspace-header">
          <div>
            <h1>{workspace?.name ?? 'Vigthoria Workbench'}</h1>
            <p>
              {workspace?.rootPath ?? 'Create a workspace to launch your agent terminals.'}
              {workspace && !rootReady && (
                <span className="workspace-header__warn"> {'—'} set your project folder below (Browse), then Apply</span>
              )}
            </p>
          </div>
          {workspace && (
            <div className="workspace-header__chips">
              {workspace.layout.panes.map((pane) => {
                const session = activeSessions.find((s) => s.paneId === pane.id);
                return (
                  <span
                    key={pane.id}
                    className={`chip ${pane.isMain ? 'chip--main' : ''} ${session?.active ? 'chip--live' : ''}`}
                  >
                    {pane.isMain ? '★ ' : ''}
                    {roleLabel(pane.role)}
                  </span>
                );
              })}
              {v4SubAgents.map((agent) => (
                <span key={agent.agentId} className={`chip chip--v4 chip--${agent.status}`}>
                  {`V4:${agent.agentId}`}
                </span>
              ))}
            </div>
          )}
        </header>

        <AuthGate />
        <AgentStatusBar />

        <section className="workspace-stage">
          {workspace ? (
            rootReady ? (
              <div className={`workspace-content ${showTools ? 'workspace-content--with-tools' : ''}`}>
                <div className="workspace-panes">
                  <PaneGrid key={`${workspace.id}-${workspace.rootPath}-${terminalEpoch}`} workspace={workspace} />
                  {showTools && <ServicesPanel />}
                </div>
                {v4SubAgents.length > 0 && activeV4Agent && (
                  <section className={`v4-subagents-panel ${v4Collapsed ? 'is-collapsed' : ''}`}>
                    <div className="v4-subagents-panel__header">
                      <div>
                        <h2>V4 Sub-Agents</h2>
                        <p>{v4SubAgents.length} active stream-backed panels</p>
                      </div>
                      <div className="v4-subagents-panel__header-actions">
                        <div className="v4-subagents-panel__view-switch">
                          <button
                            type="button"
                            className={v4View === 'canvas' ? 'is-active' : ''}
                            onClick={() => setV4View('canvas')}
                          >
                            Canvas
                          </button>
                          <button
                            type="button"
                            className={v4View === 'list' ? 'is-active' : ''}
                            onClick={() => setV4View('list')}
                          >
                            List
                          </button>
                        </div>
                        <button
                          type="button"
                          className="v4-subagents-panel__toggle"
                          onClick={() => setV4Collapsed((value) => !value)}
                        >
                          {v4Collapsed ? 'Expand' : 'Collapse'}
                        </button>
                      </div>
                    </div>
                    {!v4Collapsed && v4View === 'canvas' && (
                      <V4SubAgentCanvas
                        agents={v4SubAgents}
                        activeAgentId={activeV4Agent.agentId}
                        onSelect={setActiveV4AgentId}
                      />
                    )}
                    {!v4Collapsed && v4View === 'list' && (
                      <div className="v4-subagents-panel__tabs">
                        {v4SubAgents.map((agent) => (
                          <button
                            key={agent.agentId}
                            type="button"
                            className={`v4-subagents-panel__tab ${agent.agentId === activeV4Agent.agentId ? 'is-active' : ''}`}
                            onClick={() => setActiveV4AgentId(agent.agentId)}
                          >
                            <span>{agent.agentId}</span>
                            <span className={`chip chip--v4 chip--${agent.status}`}>{agent.status}</span>
                          </button>
                        ))}
                      </div>
                    )}
                    {!v4Collapsed && (
                      <article className="xterm-pane v4-subagent-pane">
                        <div className="xterm-pane__header">
                          <span className="xterm-pane__title">V4 Sub-Agent · {activeV4Agent.agentId}</span>
                          <span className={`xterm-pane__badge chip--${activeV4Agent.status}`}>{activeV4Agent.status}</span>
                        </div>
                        <div className="v4-subagent-pane__meta">{activeV4Agent.task}</div>
                        <div className="v4-subagent-pane__terminal">
                          <pre>{activeV4Agent.outputLog.length > 0 ? activeV4Agent.outputLog.join('\n') : 'Waiting for streamed output…'}</pre>
                        </div>
                      </article>
                    )}
                  </section>
                )}
              </div>
            ) : (
              <div className="workspace-empty workspace-empty--blocked">
                <h2>Project folder required</h2>
                <p>
                  Terminals were not started because this workspace has no valid project path yet.
                  In the sidebar, use <strong>Project folder</strong> → Browse → pick the folder that contains your <code>package.json</code>, then click <strong>Apply &amp; restart terminals</strong>.
                </p>
              </div>
            )
          ) : (
            <div className="workspace-empty">
              <VigthoriaLogo size={72} className="workspace-empty__logo" />
              <h2>Welcome to Vigthoria Workbench</h2>
              <p>Pick a preset, choose your project folder, and launch multiple terminals with a starred Main Agent pane.</p>
              <ul className="workspace-empty__list">
                <li><strong>Agent + Dev</strong> — analysis + live preview</li>
                <li><strong>Deep Analysis</strong> — agent + highlighted report panel</li>
                <li><strong>Full Stack</strong> — agent, dev server, git shell</li>
              </ul>
            </div>
          )}
        </section>

        {workspace && rootReady && (
          <div className="workspace-comfort-row">
            <AgentPromptBar />
          </div>
        )}

        <footer className="workspace-footer">
          <span className="workspace-footer__version">
            Vigthoria Workbench{appVersion ? ` v${appVersion}` : ''}
            {updateAvailable && (
              <button
                type="button"
                className="workspace-footer__update"
                onClick={() => setSettingsOpen(true)}
              >
                Update available
              </button>
            )}
          </span>
          <span>{workspace ? `${workspace.layout.panes.length} panes · ${workspace.preset}` : 'Ready'}</span>
        </footer>
      </main>
      <SettingsModal />
    </div>
  );
}
