import React from 'react'
import { useNavigate } from '@tanstack/react-router'
import { EmptyState, ToolDot } from '../../primitives'
import type { SearchRow } from '../../api/adapters'
import { highlightSnippet } from './highlightSnippet'

interface SearchTableProps {
  rows: SearchRow[]
  hasMore: boolean
  loadingMore: boolean
  onLoadMore: () => void
}

const COLS = '80px 1fr 1fr 2fr 60px'

export function SearchTable({ rows, hasMore, loadingMore, onLoadMore }: SearchTableProps): React.JSX.Element {
  const navigate = useNavigate()

  if (rows.length === 0) {
    return (
      <div className="body body-pad">
        <EmptyState glyph="∅" copy="no matches" />
      </div>
    )
  }

  return (
    <div className="search-table body">
      <div className="search-thead search-cols" style={{ gridTemplateColumns: COLS }}>
        <span>tool</span>
        <span>host</span>
        <span>cwd</span>
        <span>snippet</span>
        <span className="right">rank</span>
      </div>
      {rows.map((r, i) => (
        <div
          key={`${r.sessionId}-${r.turnId}-${i}`}
          className="search-row search-cols"
          style={{ gridTemplateColumns: COLS }}
          onClick={() => {
            void navigate({
              to: '/session/$tool/$host/$id',
              params: { tool: r.tool, host: r.host, id: r.sessionId },
              hash: `turn-${r.turnId}`,
            })
          }}
        >
          <span className="mono"><ToolDot tool={r.tool} /> {r.tool}</span>
          <span className="mono truncate">{r.host}</span>
          <span className="mono muted truncate">{r.cwd}</span>
          <span className="snippet truncate">{highlightSnippet(r.snippet)}</span>
          <span className="right mono muted">{r.rank}</span>
        </div>
      ))}
      {hasMore && (
        <div className="load-more-wrap">
          <button
            className="load-more"
            type="button"
            disabled={loadingMore}
            onClick={onLoadMore}
          >
            {loadingMore ? 'loading…' : 'load more'}
          </button>
        </div>
      )}
    </div>
  )
}
