import { useLocation } from 'react-router-dom'

import PrefetchLink from '@/components/PrefetchLink'


export default <T extends string,>({ by, label, currentOrder, defaultDirection }: {
    by:               T
    label:            string
    currentOrder:     `${ T }:${ 'asc' | 'desc' }`
    defaultDirection: Record<T, 'asc' | 'desc'> }) => {
  const [fld, dir] = currentOrder.split (':')

  const location = useLocation ()
  const qs = new URLSearchParams (location.search)
  const nextDir =
      (by === fld)
      ? (dir === 'asc' ? 'desc' : 'asc')
      : (defaultDirection[by] || 'desc')
  qs.set ('order', `${ by }:${ nextDir }`)
  qs.set ('page', '1')

  return (
      <PrefetchLink
	  className="text-inherit visited:text-inherit hover:text-inherit"
	  to={`${ location.pathname }?${ qs.toString () }`}>
	<span className="font-bold">
	  {label}
	  {by === fld && (dir === 'asc' ? ' ▲' : ' ▼')}
	</span>
      </PrefetchLink>)
}
