'use client'

import { AnchorHTMLAttributes, forwardRef, ReactNode, Ref } from 'react'

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

export interface IPktBackLink extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
  href?: string
  text?: string
  ariaLabel?: string
  renderLink?: (args: {
    href: string
    className: string
    children: ReactNode
    props: AnchorHTMLAttributes<HTMLAnchorElement>
  }) => ReactNode
  ref?: Ref<HTMLElement>
}

export const PktBackLink = forwardRef<HTMLElement, IPktBackLink>(
  ({ href = '/', text = 'Forsiden', ariaLabel, renderLink, className, ...props }, ref) => {
    const linkChildren = (
      <>
        <PktIcon className="pkt-back-link__icon pkt-icon pkt-link__icon" name="chevron-thin-left" aria-hidden="true" />
        <span className="pkt-back-link__text">{text}</span>
      </>
    )

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

    const classes = ['pkt-back-link', className].filter(Boolean).join(' ')

    return (
      <nav className={classes} aria-label={ariaLabel || 'Gå tilbake til forrige side'} ref={ref}>
        {linkRenderer({
          href,
          className: 'pkt-link pkt-link--icon-left',
          children: linkChildren,
          props,
        })}
      </nav>
    )
  },
)

PktBackLink.displayName = 'PktBackLink'
