'use client'

import classNames from 'classnames'
import { Children, cloneElement, forwardRef, type HTMLAttributes, isValidElement, ReactElement, Ref } from 'react'

import { IPktStep } from './Step'

export interface IPktStepper extends HTMLAttributes<HTMLOListElement> {
  /**
   * The index of the current active step
   */
  activeStep: number
  /**
   * Children of the Stepper must be Step items. Either an Array of Step items or a single Step item.
   */
  children: ReactElement<IPktStep>[] | ReactElement<IPktStep>
  /**
   * Additional class names
   */
  className?: string
  /**
   * Boolean to hide the content of non-active steps content
   * @default true
   */
  hideNonActiveStepsContent?: boolean
  /**
   * Boolean to hide the content and title of non-active steps
   * @default false
   */
  hideNonActiveSteps?: boolean
  /**
   * Orientation of the stepper.
   * @default vertical
   */
  orientation?: 'horizontal' | 'vertical' // default vertical
}

export const PktStepper = forwardRef(
  (
    {
      activeStep,
      className,
      children,
      hideNonActiveSteps = false,
      hideNonActiveStepsContent = true,
      orientation = 'vertical',

      ...restProps
    }: IPktStepper,
    ref: Ref<HTMLOListElement>,
  ) => {
    const stylingClasses = classNames(
      className,
      'pkt-stepper',
      orientation === 'horizontal' ? 'pkt-stepper--horizontal' : 'pkt-stepper--vertical',
    )

    const childrenWithProps = Children.map(children, (child, index) => {
      if (isValidElement(child)) {
        return cloneElement(child, {
          className: classNames(child.props.className, {
            'pkt-step--hideStep': hideNonActiveSteps && index !== activeStep,
            'pkt-step--hideContent': hideNonActiveStepsContent && index !== activeStep,
          }),
        })
      }
      return child
    })

    return (
      <ol data-testid="pkt-stepper" className={stylingClasses} ref={ref} {...restProps}>
        {childrenWithProps}
      </ol>
    )
  },
)

PktStepper.displayName = 'PktStepper'
