import { SortOrder, useCallbackRef, useControlled } from '../utils'
import { UseTableProps } from './useTable.types'

const sortOrders: SortOrder[] = ['asc', 'desc', null]
const defaultSortOrder: SortOrder = sortOrders[0]

function getNextOrder(order: SortOrder) {
  const next = sortOrders.indexOf(order) + 1
  return sortOrders[next] !== undefined ? sortOrders[next] : defaultSortOrder
}

/** Handles controlled/uncontrolled sort of the Table rows. */
export default function useTable(props: UseTableProps) {
  const { defaultSort = { key: '', order: defaultSortOrder }, onSortChange: onSortChangeProp, sort: value } = props
  const [sort, onChange, { isControlled }] = useControlled({
    defaultValue: defaultSort,
    onChange: onSortChangeProp,
    value,
  })

  const onSortChange = useCallbackRef((key: string) => {
    const order = sort.key === key ? getNextOrder(sort.order) : defaultSortOrder
    onChange({ key, order })
  })

  return { isControlled, onSortChange, sort }
}

export type UseTableReturnType = ReturnType<typeof useTable>
