import React, { forwardRef } from 'react'
import { Link as RouterLink, LinkProps } from 'react-router-dom'

import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'

interface BaseProps {
  disabled?: boolean
  onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void
  noTrack?: boolean
  eventParams?: { [key: string]: any }
}

interface NoTrack extends BaseProps {
  noTrack: true
  eventName?: string
}

interface Event extends BaseProps {
  noTrack?: false
  eventName: string
}

type Props = NoTrack | Event

type AProps = Props & {
  href: string
  to?: any
  target?: React.HTMLAttributeAnchorTarget
}

type LinkStrictProps = Props & LinkProps

export type EventLinkProps =
  | AProps
  | (LinkStrictProps & {
      className?: string
      children?: React.ReactNode
    })

const Link = forwardRef<HTMLAnchorElement, EventLinkProps>((props, ref) => {
  const { store } = useStores()

  const { eventName = '', noTrack, eventParams, href, onClick, to, disabled, ...rest } = props
  const clickHandler = (e: React.MouseEvent<HTMLAnchorElement>) => {
    if (disabled) {
      return
    }

    // the priority notack is Higher than eventName
    if (!noTrack) {
      const currentCluster = store.currentCluster || null

      eventTracking(eventName, {
        'Cluster Type': currentCluster ? currentCluster.computed.clusterType : '',
        ...eventParams
      })
    }

    onClick && onClick(e)
  }

  return href ? (
    <a onClick={clickHandler} href={href} {...rest} ref={ref} />
  ) : (
    <RouterLink to={to} onClick={clickHandler} ref={ref} {...rest} />
  )
})

export const RefLink = forwardRef<
  HTMLAnchorElement,
  EventLinkProps & { children?: React.ReactNode; className?: string }
>((props, ref) => {
  const { children, ...rest } = props
  return (
    <Link {...rest} ref={ref} type={undefined}>
      {children}
    </Link>
  )
})

export default Link
