import { Checkbox, Icon, IconSize } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import { ellipsized } from '@inject/shared/css/textOverflow'
import { useCallback } from 'react'
import {
  checkbox,
  selectHeaderCell,
  sticky,
  tableCell,
  verticallyCentered,
} from './classes'
import { SortingOrder, type HeadProps } from './typing'

const Head = <T,>({
  columns,
  sortByColumnId,
  setSortByColumnId,
  sortingOrders,
  setSortingOrders,
  allSelected,
  onSelectAll,
  onDeselectAll,
}: HeadProps<T>) => {
  const handleClick = useCallback(
    (columnId: string) => {
      if (columnId === sortByColumnId) {
        setSortingOrders(prev => ({
          ...prev,
          [columnId]:
            prev[columnId] === SortingOrder.ASC
              ? SortingOrder.DESC
              : SortingOrder.ASC,
        }))
      } else {
        setSortByColumnId(columnId)
      }
    },
    [setSortByColumnId, setSortingOrders, sortByColumnId]
  )

  return (
    <thead>
      <tr>
        {onSelectAll && (
          <th className={cx(sticky, tableCell, selectHeaderCell)}>
            <Checkbox
              className={checkbox}
              checked={allSelected}
              onChange={allSelected ? onDeselectAll : onSelectAll}
            />
          </th>
        )}
        {columns.map(column => (
          <th
            key={column.id}
            className={cx(
              sticky,
              tableCell,
              ellipsized,
              css`
                text-align: left;
              `,
              column.className
            )}
            style={column.style}
            title={column.name}
          >
            <div
              className={cx(
                ellipsized,
                verticallyCentered,
                css`
                  justify-content: space-between;
                `
              )}
            >
              <div
                className={cx(
                  ellipsized,
                  css`
                    flex: 1;
                  `
                )}
                title={column.name}
              >
                {column.name}
              </div>
              {column.sortingFunction && (
                <Icon
                  icon={
                    sortingOrders[column.id] === SortingOrder.ASC
                      ? 'arrow-up'
                      : 'arrow-down'
                  }
                  color={
                    sortByColumnId === column.id
                      ? 'rgb(95, 107, 124)'
                      : 'rgba(95, 107, 124, 0.5)'
                  }
                  style={{ cursor: 'pointer' }}
                  size={IconSize.LARGE}
                  onClick={() => {
                    handleClick(column.id)
                  }}
                />
              )}
            </div>
          </th>
        ))}
      </tr>
    </thead>
  )
}

export default Head
