import { useNavigate } from '@/router'
import type { AnchorButtonProps } from '@blueprintjs/core'
import { AnchorButton } from '@blueprintjs/core'
import { type FC } from 'react'
import { generatePath, useHref } from 'react-router-dom'

export type LinkType = Parameters<ReturnType<typeof useNavigate>>

export interface LinkButtonProps {
  link?: LinkType
  button: AnchorButtonProps
}

const LinkButton: FC<LinkButtonProps> = ({ link, button }) => {
  const nav = useNavigate()

  const href = useHref(
    /*
     * this has to be done with apply to ensure type safety between
     * link.to and link.params
     */
    link ? generatePath.apply(null, [link[0].toString(), link[1]?.params]) : '.'
  )

  return (
    <AnchorButton
      {...button}
      href={link ? href : undefined}
      onClick={e => {
        button.onClick?.(e)

        if (link) {
          // prevent default navigation using anchor to avoid page reload
          e.preventDefault()

          /*
           * this has to be done with apply to ensure type safety between
           * link.to and link.params
           */
          // eslint-disable-next-line prefer-spread
          nav.apply(null, link)
        }
      }}
    />
  )
}

export default LinkButton
