'use client'

import { forwardRef, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react'

import { PktIcon } from '../icon/Icon'
import { type IPktTag, PktTag } from '../tag/Tag'
import { useTabsContext } from './Tabs'

export type TSkin = IPktTag['skin']

export interface IPktTabItem {
  children: ReactNode
  active?: boolean
  disabled?: boolean
  href?: string
  onClick?: (event: MouseEvent) => void
  icon?: string
  controls?: string
  tag?: string
  tagSkin?: TSkin
  index?: number
}

export const PktTabItem = forwardRef<HTMLAnchorElement | HTMLButtonElement, IPktTabItem>(
  ({ children, active, disabled = false, href, onClick, icon, controls, tag, tagSkin, index = 0 }, ref) => {
    const { arrowNav, registerTabRef, handleKeyPress, selectTab } = useTabsContext()
    const isActive = !!active && !disabled

    const handleClick = (event: MouseEvent<HTMLAnchorElement | HTMLButtonElement>) => {
      if (disabled) {
        event.preventDefault()
        event.stopPropagation()
        return
      }
      selectTab(index)
      onClick?.(event)
    }

    const handleKeyDown = (event: KeyboardEvent<HTMLAnchorElement | HTMLButtonElement>) => {
      if (disabled && (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar')) {
        event.preventDefault()
        event.stopPropagation()
        return
      }

      handleKeyPress(index, event)
    }

    const commonProps = {
      'aria-selected': arrowNav ? isActive : undefined,
      'aria-controls': controls,
      role: arrowNav ? 'tab' : undefined,
      onKeyDown: handleKeyDown,
      onClick: handleClick,
      tabIndex: disabled ? -1 : isActive || !arrowNav ? undefined : -1,
      ref: (el: HTMLAnchorElement | HTMLButtonElement | null) => {
        registerTabRef(index, el, disabled)
        if (typeof ref === 'function') {
          ref(el)
        } else if (ref) {
          ref.current = el
        }
      },
    }

    const content = (
      <>
        {icon && <PktIcon name={icon} className="pkt-icon--small" />}
        {children}
        {tag && (
          <PktTag skin={tagSkin} size="small">
            {tag}
          </PktTag>
        )}
      </>
    )

    if (href) {
      return (
        <a
          {...commonProps}
          href={disabled ? undefined : href}
          aria-disabled={disabled || undefined}
          className={`pkt-tabs__link ${isActive ? 'active' : ''} ${disabled ? 'pkt-tabs__item--disabled' : ''}`}
        >
          {content}
        </a>
      )
    }

    return (
      <button
        {...commonProps}
        type="button"
        disabled={disabled}
        aria-disabled={disabled || undefined}
        className={`pkt-tabs__button pkt-link-button ${isActive ? 'active' : ''} ${disabled ? 'pkt-tabs__item--disabled' : ''}`}
      >
        {content}
      </button>
    )
  },
)

PktTabItem.displayName = 'PktTabItem'
