'use client'

import classNames from 'classnames'
import { AnchorHTMLAttributes, FC, LinkHTMLAttributes, ReactNode } from 'react'

import { PktIcon } from '../icon/Icon'

interface IPktLink extends LinkHTMLAttributes<HTMLAnchorElement> {
  href?: string
  iconName?: string | undefined
  className?: string | undefined
  iconPosition?: string | undefined
  external?: boolean
  target?: string | undefined
  renderLink?: (args: {
    href: string
    className: string
    children: ReactNode
    props: AnchorHTMLAttributes<HTMLAnchorElement>
  }) => ReactNode
}

export const PktLink: FC<IPktLink> = ({
  href,
  iconName,
  className,
  iconPosition,
  external,
  target,
  renderLink,
  children,
  ...props
}: IPktLink) => {
  const classes = {
    'pkt-link': true,
    'pkt-link--icon-left': (!!iconName && iconPosition === 'left') || !!(iconName && !iconPosition),
    'pkt-link--icon-right': !!iconName && iconPosition === 'right',
    'pkt-link--external': external,
  }

  const linkChildren = (
    <>
      {iconName && <PktIcon name={iconName} className="pkt-link__icon" />}
      {children}
    </>
  )

  const linkRenderer =
    renderLink ||
    (({ href, className, children, props }) => (
      <a href={href} className={className} {...props}>
        {children}
      </a>
    ))

  return linkRenderer({
    href: href ?? '',
    className: classNames(classes, className),
    children: linkChildren,
    props: {
      ...props,
      target,
      rel: external ? 'noopener noreferrer' : undefined,
    },
  })
}

PktLink.displayName = 'PktLink'
