import React from 'react'
import { EmptyState } from '../../primitives'
import { ToolDot } from '../../primitives'
import type { Session } from '../../api/adapters'

interface SessionsTableProps {
  sessions: Session[]
  cursor: number
  onCursor: (i: number) => void
  onOpen: (s: Session) => void
}

const COLS = '120px 110px 70px 1fr 50px 60px 90px'

// Format STARTED column: ≤24h → "14:22"; older → "Apr 25 11:08"
function formatStarted(isoStr: string): string {
  const d = new Date(isoStr)
  const now = new Date()
  const diffMs = now.getTime() - d.getTime()
  const h24 = 24 * 60 * 60 * 1000

  if (diffMs <= h24) {
    return d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false })
  }
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) +
    ' ' + d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false })
}

// Format TOK: 12400 → "12.4k"; small numbers unchanged
function formatTok(n: number): string {
  if (n >= 1000) {
    return (n / 1000).toFixed(1) + 'k'
  }
  return String(n)
}

export function SessionsTable({ sessions, cursor, onCursor, onOpen }: SessionsTableProps): React.JSX.Element {
  if (sessions.length === 0) {
    return (
      <div className="body body-pad">
        <EmptyState glyph="∅" copy="no sessions match these filters" />
      </div>
    )
  }

  return (
    <div className="home-table body">
      <div className="home-thead home-cols" style={{ gridTemplateColumns: COLS }}>
        <span>started</span>
        <span>tool</span>
        <span>host</span>
        <span>summary</span>
        <span className="right">turns</span>
        <span className="right">tok</span>
        <span>cwd</span>
      </div>
      {sessions.map((s, i) => {
        const isCursor = i === cursor
        return (
          <div
            key={s.id}
            className={'home-row home-cols' + (isCursor ? ' cursor' : '')}
            style={{ gridTemplateColumns: COLS }}
            onClick={() => { onCursor(i); onOpen(s) }}
            onMouseEnter={() => onCursor(i)}
          >
            <span className="mono muted">{formatStarted(s.started)}</span>
            <span className="mono">
              <ToolDot tool={s.tool} />
              {' '}{s.tool}
            </span>
            <span className="mono">{s.host}</span>
            <span className="truncate">{s.summary}</span>
            <span className="right mono">{s.turns}</span>
            <span className="right mono muted">{formatTok(s.tokensIn + s.tokensOut)}</span>
            <span className="mono muted truncate">{s.cwd}</span>
          </div>
        )
      })}
    </div>
  )
}
