import type { ReactElement } from "react";
import type { SessionTab } from "../../types/domain";
import { shortToken, toneClass } from "../../utils";

interface SessionSidebarProps {
  tabs: SessionTab[];
  loading: boolean;
  modelLabel: string;
  disabled?: boolean;
  onCreate(): void;
  onDelete(): void;
  onSelect(tab: SessionTab): void;
}

export function SessionSidebar({ tabs, loading, modelLabel, disabled = false, onCreate, onDelete, onSelect }: SessionSidebarProps): ReactElement {
  const active = tabs.find((tab) => tab.active) ?? null;
  return (
    <aside className="session-sidebar" id="session-sidebar" aria-label="Code Agent sessions">
      <header className="session-sidebar-head">
        <div>
          <p className="eyebrow">Sessions</p>
          <h2>Agent Sessions</h2>
        </div>
        <button className="session-icon-button" id="session-create" type="button" aria-label="创建 session" title="创建 session" disabled={disabled} onClick={onCreate}>+</button>
      </header>
      <div className="session-model-channel" id="session-model-channel" aria-live="polite">模型通道：{modelLabel}</div>
      <div className="session-tabs" id="session-tabs" role="tablist" aria-label="Code Agent sessions">
        {tabs.length === 0 ? <p className="session-empty">还没有 session。</p> : tabs.map((tab) => <SessionTabButton key={tab.key} tab={tab} disabled={disabled} onSelect={onSelect} />)}
      </div>
      <div className="session-sidebar-foot">
        <span className="session-status" id="session-status">{loading ? "加载中" : active ? `当前 ${shortToken(active.sessionId ?? active.conversationId, 8)}` : "等待 workspace"}</span>
        <button className="session-delete-button" id="session-delete" type="button" disabled={disabled || !active} onClick={onDelete}>删除当前</button>
      </div>
    </aside>
  );
}

function SessionTabButton({ tab, disabled, onSelect }: { tab: SessionTab; disabled: boolean; onSelect(tab: SessionTab): void }): ReactElement {
  return (
    <button type="button" className={`session-tab tone-border-${toneClass(tab.status)}`} role="tab" aria-selected={tab.active} title={`conversation=${tab.conversationId ?? "unknown"} / session=${tab.sessionId ?? "unknown"} / trace=${tab.lastTraceId ?? "unknown"}`} disabled={disabled} onClick={() => onSelect(tab)}>
      <span className="session-tab-label">{tab.label}</span>
      <span className="session-tab-subtitle">{tab.subtitle}</span>
      <span className="session-tab-count">{tab.messageCount} 条</span>
    </button>
  );
}
