import React, { useCallback } from 'react'
import { useLocation, useNavigate, useHref } from 'react-router-dom'

import { StyledButton } from './style'


export type ButtonLinkProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
  to: string
}

/**
 * Almost same as `react-router-dom`'s `NavLink` except it uses a button element instead
 * of an anchor element. Which means there's no `href`, thus no link preview on hover,
 * and no 'Open link in new tab'.
 *
 * Just like `NavLink`, this component also adds an `.active` classname if the current path
 * is same as the one being reference by the `to` prop.
 */
export const ButtonLink = ({ to, children, className, onClick, ...rest }: ButtonLinkProps) => {
  const href = useHref(to)
  const isActive = useLocation().pathname === href
  const navigate = useNavigate()

  const handleClick = useCallback(
    (e: React.MouseEvent<HTMLButtonElement>) => {
      onClick?.(e)

      if (!e.defaultPrevented) {
        navigate(href)
      }
    },
    [href, navigate, onClick]
  )

  return (
    <StyledButton onClick={handleClick} className={`${className}${isActive ? ' active' : ''}`} {...rest}>
      {children}
    </StyledButton>
  )
}
