'use client'

import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { useTransition } from 'react'

type Props = {
  /** Column key — written into the URL as `?sort=<key>`. */
  sortKey: string
  /** Header label. */
  children: React.ReactNode
  /** Default sort direction the first time this column is clicked. */
  defaultDir?: 'asc' | 'desc'
  /** Right-align (for numeric columns). */
  numeric?: boolean
}

/**
 * Clickable table header that flips the `?sort` and `?dir` URL params.
 * The server reads them and applies an `.order()` clause to the SQL query.
 * Default behavior: first click sorts by this column in `defaultDir`
 * (desc for numeric, asc for text). Subsequent clicks flip the direction.
 */
export function SortableHeader({
  sortKey,
  children,
  defaultDir,
  numeric = false,
}: Props) {
  const router = useRouter()
  const pathname = usePathname()
  const params = useSearchParams()
  const [, startTransition] = useTransition()

  const currentSort = params.get('sort')
  const currentDir = (params.get('dir') ?? 'desc') as 'asc' | 'desc'
  const active = currentSort === sortKey
  const indicator = active ? (currentDir === 'asc' ? ' ▲' : ' ▼') : ''

  function click() {
    const next = new URLSearchParams(params)
    const initialDir = defaultDir ?? (numeric ? 'desc' : 'asc')
    if (currentSort !== sortKey) {
      next.set('sort', sortKey)
      next.set('dir', initialDir)
    } else {
      next.set('dir', currentDir === 'asc' ? 'desc' : 'asc')
    }
    next.delete('page')
    startTransition(() => {
      router.push(`${pathname}?${next.toString()}`, { scroll: false })
    })
  }

  return (
    <button
      type="button"
      onClick={click}
      style={{
        background: 'transparent',
        color: active ? '#1a1a1a' : '#555',
        border: 'none',
        padding: 0,
        font: 'inherit',
        cursor: 'pointer',
        textTransform: 'inherit',
        letterSpacing: 'inherit',
        textAlign: numeric ? 'right' : 'left',
        width: '100%',
        fontWeight: 'inherit',
      }}
    >
      {children}
      <span style={{ opacity: 0.6 }}>{indicator}</span>
    </button>
  )
}
