import type { JSX } from "react"
import { useCallback } from "react"
import { SortableHeader, TableHead } from "../Table"

interface TableHeaderProps {
  header: any
  getWidthStyle: (column: any) => React.CSSProperties
  renderHeaderContent: (header: any) => React.ReactNode
}

export function TableHeaderComponent({
  header,
  getWidthStyle,
  renderHeaderContent,
}: TableHeaderProps): JSX.Element {
  const renderSortableHeader = useCallback(
    (header: any) => (
      <SortableHeader
        key={header.id}
        isSorted={!!header.column.getIsSorted()}
        isSortedDesc={header.column.getIsSorted() === "desc"}
        onSort={direction => header.column.toggleSorting(direction === "desc")}
        onHide={() => header.column.toggleVisibility(false)}
        style={getWidthStyle(header.column)}
      >
        {renderHeaderContent(header)}
      </SortableHeader>
    ),
    [getWidthStyle, renderHeaderContent],
  )

  const renderRegularHeader = useCallback(
    (header: any) => (
      <TableHead key={header.id} style={getWidthStyle(header.column)}>
        {renderHeaderContent(header)}
      </TableHead>
    ),
    [getWidthStyle, renderHeaderContent],
  )

  return header.column.getCanSort() ? renderSortableHeader(header) : renderRegularHeader(header)
}
