import { useNavigate } from '@/router'
import type { AnchorButtonProps } from '@blueprintjs/core'
import { AnchorButton } from '@blueprintjs/core'
import { Dot } from '@blueprintjs/icons/lib/esm/generated/16px/paths'
import { css } from '@emotion/css'
import { type FC } from 'react'
import { generatePath, useHref, useMatch } from 'react-router-dom'

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

export interface LinkButtonProps {
  link?: LinkType
  button: AnchorButtonProps
  end?: boolean
  disableActive?: boolean
  className?: string
}

const defaultClass = css`
  &.bp5-intent-warning > .bp5-icon:first-child {
    position: relative;
  }
  &.bp5-intent-warning > .bp5-icon:first-child::after {
    content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' data-icon='dot' width='30' height='30' viewBox='0 0 20 20'%3E%3Cpath stroke=%22%23CD4246%22 fill=%22%23CD4246%22 d=%22${Dot}%22%3E%3C/path%3E%3C/svg%3E");
    color: red;
    position: absolute;
    stroke: red;
    bottom: -8px;
    right: -16px;
  }
`

const LinkButton: FC<LinkButtonProps> = ({
  link,
  button,
  end,
  disableActive,
  className,
}) => {
  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]) : '.'
  )
  const active = useMatch({
    path: href,
    end: !!end,
  })

  return (
    <AnchorButton
      className={className ? className : defaultClass}
      active={!!active && !disableActive}
      {...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
