import type { NonIdealStateProps } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import { useMemo, type CSSProperties } from 'react'
import Body from './Body'
import Head from './Head'
import type { Column, Row } from './typing'

const wrapper = css`
  height: 100%;
  overflow-y: auto;
`

const table = css`
  border-collapse: collapse;
  table-layout: fixed;
  width: 100%;
`

type TableProps<T> = {
  columns: Column<T>[]
  className?: string
  style?: CSSProperties
  loading?: boolean
  rows: Row<T>[]
  noDataStateProps?: NonIdealStateProps
}

const Table = <T,>({
  columns: columnsUnfiltered,
  className,
  style,
  loading,
  rows,
  noDataStateProps,
}: TableProps<T>) => {
  const columns = useMemo(
    () => columnsUnfiltered.filter(column => column.display !== false),
    [columnsUnfiltered]
  )

  return (
    <div className={cx(className, wrapper)}>
      <table style={style} className={table}>
        <Head columns={columns} />
        <Body
          columns={columns}
          loading={loading}
          rows={rows}
          noDataStateProps={noDataStateProps}
        />
      </table>
    </div>
  )
}

export default Table
