import * as React from 'react'
import { cn } from './cva'

export interface TableProps {
  caption?: string
  children: React.ReactNode
  className?: string
}

export interface ThProps extends React.ThHTMLAttributes<HTMLTableCellElement> {
  scope?: 'col' | 'row'
  sort?: 'asc' | 'desc' | 'none'
  onSort?: () => void
}

const tableClass = 'w-full border-collapse text-fg text-sm'
const headClass = 'border-b border-border bg-surface-raised'
const rowClass = 'border-b border-border'
const cellClass = 'px-3 py-2 text-left align-middle'
const thClass = cn(cellClass, 'font-semibold text-fg')
const sortButtonClass =
  'inline-flex w-full items-center gap-1 bg-transparent text-inherit font-semibold focus-visible:outline focus-visible:outline-accent rounded-sm'

function TableRoot({ caption, children, className }: TableProps) {
  return (
    <table className={cn(tableClass, className)}>
      {caption ? <caption className="px-3 py-2 text-left text-sm font-semibold text-fg">{caption}</caption> : null}
      {children}
    </table>
  )
}

function TableHead({ children, className, ...props }: React.HTMLAttributes<HTMLTableSectionElement>) {
  return (
    <thead className={cn(headClass, className)} {...props}>
      {children}
    </thead>
  )
}

function TableBody({ children, className, ...props }: React.HTMLAttributes<HTMLTableSectionElement>) {
  return (
    <tbody className={className} {...props}>
      {children}
    </tbody>
  )
}

function TableRow({ children, className, ...props }: React.HTMLAttributes<HTMLTableRowElement>) {
  return (
    <tr className={cn(rowClass, className)} {...props}>
      {children}
    </tr>
  )
}

function TableTh({ scope = 'col', sort, onSort, children, className, ...props }: ThProps) {
  const ariaSort =
    sort === 'asc' ? 'ascending' : sort === 'desc' ? 'descending' : sort === 'none' ? 'none' : undefined

  return (
    <th scope={scope} aria-sort={ariaSort} className={cn(thClass, className)} {...props}>
      {sort !== undefined && onSort ? (
        <button type="button" className={sortButtonClass} onClick={onSort}>
          {children}
        </button>
      ) : (
        children
      )}
    </th>
  )
}

function TableTd({ children, className, ...props }: React.TdHTMLAttributes<HTMLTableCellElement>) {
  return (
    <td className={cn(cellClass, className)} {...props}>
      {children}
    </td>
  )
}

export const Table = Object.assign(TableRoot, {
  Head: TableHead,
  Body: TableBody,
  Row: TableRow,
  Th: TableTh,
  Td: TableTd,
})
