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

type TableRootProps = React.HTMLAttributes<HTMLTableElement> & {
  ref?: React.Ref<HTMLTableElement>
}

const TableRoot = ({ className, ref, ...props }: TableRootProps) => (
  <div className="relative w-full overflow-auto">
    <table
      ref={ref}
      className={cn('w-full border-collapse', className)}
      {...props}
    />
  </div>
)
TableRoot.displayName = 'TableRoot'

type TableSectionProps = React.HTMLAttributes<HTMLTableSectionElement> & {
  ref?: React.Ref<HTMLTableSectionElement>
}

const TableHeader = ({ className, ref, ...props }: TableSectionProps) => (
  <thead
    ref={ref}
    className={cn(
      'w-full border-b border-border [&_tr:first-child]:hover:bg-transparent',
      className,
    )}
    {...props}
  />
)
TableHeader.displayName = 'TableHeader'

const TableBody = ({ className, ref, ...props }: TableSectionProps) => (
  <tbody ref={ref} className={cn('w-full', className)} {...props} />
)
TableBody.displayName = 'TableBody'

type TableRowProps = React.HTMLAttributes<HTMLTableRowElement> & {
  ref?: React.Ref<HTMLTableRowElement>
}

const TableRow = ({ className, ref, ...props }: TableRowProps) => (
  <tr
    ref={ref}
    className={cn(
      'group/row w-full border-0 border-b border-solid border-border px-2 transition-colors hover:bg-background-alt',
      className,
    )}
    {...props}
  />
)
TableRow.displayName = 'TableRow'

type TableHeadProps = React.ThHTMLAttributes<HTMLTableCellElement> & {
  ref?: React.Ref<HTMLTableCellElement>
}

const TableHead = ({ className, ref, ...props }: TableHeadProps) => (
  <th
    ref={ref}
    className={cn(
      'h-20 items-center text-nowrap p-4 text-left text-sm font-semibold text-muted-more-foreground [&:first-child]:pl-2 [&:last-child]:pr-2',
      className,
    )}
    {...props}
  />
)
TableHead.displayName = 'TableHead'

type TableCellProps = React.TdHTMLAttributes<HTMLTableCellElement> & {
  dataCell?: boolean
  ref?: React.Ref<HTMLTableCellElement>
}

const TableCell = ({ className, ref, ...props }: TableCellProps) => (
  <td
    ref={ref}
    className={cn(
      'h-20 text-nowrap p-4 align-middle text-sm font-normal text-foreground [&:first-child]:pl-2 [&:last-child]:pr-2',
      className,
    )}
    {...props}
  />
)
TableCell.displayName = 'TableCell'

export { TableRoot, TableHeader, TableBody, TableHead, TableRow, TableCell }
