import { useNavigate, useSearch } from '@tanstack/react-router'
import type { PaginationInput } from '@lunarfront/shared/schemas'

interface PaginationSearch {
  page?: number
  limit?: number
  q?: string
  sort?: string
  order?: 'asc' | 'desc'
}

export function usePagination() {
  const search = useSearch({ strict: false }) as PaginationSearch
  const navigate = useNavigate()

  const params: PaginationInput = {
    page: search.page ?? 1,
    limit: search.limit ?? 25,
    q: search.q,
    sort: search.sort,
    order: search.order ?? 'asc',
  }

  function setParams(updates: Partial<PaginationSearch>) {
    navigate({
      // @ts-expect-error: navigate without a route context resolves search as never; safe here since we use strict:false
      search: (prev: any) => ({
        ...prev,
        ...updates,
        // Reset to page 1 when search or sort changes
        page: updates.q !== undefined || updates.sort !== undefined ? 1 : (updates.page ?? (prev as PaginationSearch).page),
      }),
      replace: true,
    })
  }

  return {
    ...params,
    setPage: (page: number) => setParams({ page }),
    setSearch: (q: string) => setParams({ q: q || undefined }),
    setSort: (sort: string, order: 'asc' | 'desc') => setParams({ sort, order }),
    params,
  }
}
