import type { SessionSummary } from "@qjclaw/shared-types"

type SendPhase = "idle" | "preparing" | "streaming" | "finalizing"

interface SessionListProps {
  visible: boolean
  label: string
  sessions: SessionSummary[]
  activeSessionId: string
  sessionTitles: Record<string, string>
  projectActionPending: boolean
  sendPhase: SendPhase
  activeStreamSessionId?: string
  closeLabel: string
  formatSessionTitle(title: string, index: number): string
  onOpenSession(sessionId: string): void
  onCloseSession(sessionId: string): void
}

export function SessionList({
  visible,
  label,
  sessions,
  activeSessionId,
  sessionTitles,
  projectActionPending,
  sendPhase,
  activeStreamSessionId,
  closeLabel,
  formatSessionTitle,
  onOpenSession,
  onCloseSession
}: SessionListProps) {
  if (!visible) {
    return null
  }

  return (
    <section className="sidebar-section sidebar-section-fill compact sidebar-session-section">
      <div className="sidebar-section-head sidebar-section-head-subtle">
        <div className="sidebar-section-copy">
          <span className="sidebar-section-label">{label}</span>
        </div>
      </div>
      <div className="sidebar-session-list">
        {sessions.map((session, index) => (
          <div key={session.id} className={"sidebar-session-card" + (activeSessionId === session.id ? " active" : "")}>
            <button type="button" className="sidebar-session-main app-no-drag" disabled={projectActionPending} onClick={() => onOpenSession(session.id)}>
              <strong>{sessionTitles[session.id] ?? formatSessionTitle(session.title, index)}</strong>
            </button>
            {sessions.length > 1 ? (
              <button
                type="button"
                className="sidebar-session-close app-no-drag"
                aria-label={closeLabel}
                title={closeLabel}
                disabled={projectActionPending || (sendPhase !== "idle" && activeStreamSessionId === session.id)}
                onClick={() => onCloseSession(session.id)}
              >
                x
              </button>
            ) : null}
          </div>
        ))}
      </div>
    </section>
  )
}
