import type { JSX } from 'react'
import { DataTable, withColumnResizing, withSearch, withSorting, type DataTableColumn } from './internal/DataTable'
import { useDeckTooltip } from './DeckTooltip'
import { formatRelativeTime } from './format'
import { safeHttpUrl } from './safe-url'

export interface AbandonedPlanItem {
  runId: string
  slug: string
  title: string
  projectLabel: string
  failLabel: string | null
  abandonedAtMs: number
  href: string
}

function abandonedColumns(onRestore: (item: AbandonedPlanItem) => void): DataTableColumn<AbandonedPlanItem>[] {
 return [
  { id: 'plan', header: 'Plan', minWidth: 128, sortable: true, sortValue: (item) => (item.title || item.slug).toLowerCase(), searchValue: (item) => `${item.title} ${item.slug}`, cell: (item) => { const title = item.title || item.slug; return <><a href={safeHttpUrl(item.href)} className="font-semibold text-fg no-underline hover:text-accent">{title}</a>{item.title && <span className="block font-mono text-[10px] text-fg-subtle">{item.slug}</span>}</> } },
  { id: 'project', header: 'Project', minWidth: 76, sortable: true, sortValue: (item) => item.projectLabel.toLowerCase(), searchValue: (item) => item.projectLabel, cell: (item) => <span className="text-fg-muted">{item.projectLabel}</span> },
  { id: 'failure', header: 'Failed how', minWidth: 92, sortable: true, sortValue: (item) => (item.failLabel ?? '').toLowerCase(), searchValue: (item) => item.failLabel ?? '', cell: (item) => <span data-testid="abandoned-fail-label" className="font-mono text-fg-muted">{item.failLabel ?? '—'}</span> },
  { id: 'abandoned', header: 'Abandoned', minWidth: 76, sortable: true, sortValue: (item) => item.abandonedAtMs, cell: (item) => <AbandonedTimeCell item={item} /> },
  { id: 'restore', header: 'Restore', minWidth: 72, cell: (item) => <div className="text-right"><button type="button" aria-label={`Restore ${item.title || item.slug}`} onClick={() => onRestore(item)} className="inline-flex min-h-11 items-center rounded-md border border-border bg-surface px-3 text-xs font-semibold text-fg hover:border-border-strong hover:bg-surface-raised focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent">Restore</button></div> },
 ]
}

function AbandonedTimeCell({ item }: { item: AbandonedPlanItem }): JSX.Element {
  const absoluteTime = new Date(item.abandonedAtMs).toISOString()
  const timeTooltip = useDeckTooltip(absoluteTime, 'Abandoned at')
  return <time className="text-fg-muted" dateTime={absoluteTime} {...timeTooltip}>{formatRelativeTime(item.abandonedAtMs)}</time>
}

export function AbandonedPlansTable(props: {
  items: AbandonedPlanItem[]
  onRestore(item: AbandonedPlanItem): void
}): JSX.Element {
  if (props.items.length === 0) {
    return (
      <p className="px-6 py-12 text-center text-sm text-fg-muted">
        No abandoned <a href="/plans" className="font-semibold text-accent">plans</a>. Failed plans you
        abandon land here — nothing is ever hard-deleted.
      </p>
    )
  }

  return (
    <div className="rounded-lg border border-border bg-surface"><DataTable caption="Abandoned plans" columns={abandonedColumns(props.onRestore)} rows={props.items} getRowId={(item) => item.runId} capabilities={[withSorting(), withSearch({ label: 'Search abandoned plans' }), withColumnResizing()]} /></div>
  )
}
