'use client'
import { useSearchParams } from 'next/navigation'
import { useRouter } from 'next/router'
import { useCallback, useEffect, useState } from 'react'

import { TPageSizeOption, TPaginationModel } from '../types/api'
import { defaultPageSize } from '../utils'

const usePagination = (props: TPaginationModel = { with_paginate: 'yes' }) => {
  const router = useRouter()
  const params = useSearchParams()

  const [paginationModel, setPaginationModel] = useState<TPaginationModel>({
    page:
      (props?.page && props.page > 0 ? props.page : null) ??
      (router.isReady && router.query['page'] ? +router.query['page'] : 1),
    per_page:
      props?.per_page ??
      (router.isReady && router.query['per_page'] ? (+router.query['per_page'] as TPageSizeOption) : defaultPageSize),
    with_paginate: props?.with_paginate === 'no' ? 'no' : 'yes'
  })

  const setPagination = useCallback(
    (model: TPaginationModel) => {
      setPaginationModel(prev => {
        return {
          ...prev,
          page: !model?.page
            ? params.get('page')
              ? Number(params.get('page')) >= 0
                ? Number(params.get('page'))
                : 1
              : 1
            : model.page >= 0
              ? model.page
              : 1,
          per_page: model?.per_page
            ? (model.per_page as any)
            : params.get('per_page')
              ? Number(params.get('per_page'))
              : (defaultPageSize as number)
        }
      })
      router?.replace({
        query: {
          ...router.query,
          page: model.page ? model.page : 1,
          per_page: model.per_page ? model.per_page : defaultPageSize
        }
      })
    },
    [props]
  )

  useEffect(() => {
    if (props?.page && props?.page !== paginationModel.page)
      setPaginationModel(prev => ({
        ...prev,
        page: !paginationModel?.page
          ? params.get('page')
            ? Number(params.get('page')) > 0
              ? Number(params.get('page'))
              : 1
            : 1
          : paginationModel.page >= 0
            ? paginationModel.page
            : 1
      }))
  }, [props?.page])

  useEffect(() => {
    if (props?.per_page && props?.per_page !== paginationModel.per_page)
      setPaginationModel(prev => ({
        ...prev,
        per_page: params.get('per_page')
          ? Number(params.get('per_page'))
          : paginationModel?.per_page
            ? (paginationModel.per_page as number)
            : (defaultPageSize as number as any)
      }))
  }, [props?.per_page])

  return { paginationModel, setPagination }
}

export default usePagination
