import cx from "classnames";
import React from "react";

export const showTitlesFromOptions = ["md", "lg", "xl"] as const;
export const variantOptions = ["default", "inverse"] as const;

export type ShowTitlesFrom = (typeof showTitlesFromOptions)[number];

export interface StepbarStep {
  href?: string;
  isCurrent?: boolean;
  title: React.ReactNode;
}

export interface StepbarProps extends React.HTMLAttributes<HTMLElement> {
  /** Arial label of nav element */
  label?: string;
  /** Titles of non-current steps are visible from this breakpoint */
  showTitlesFrom?: ShowTitlesFrom;
  /** Array of step objects */
  steps: StepbarStep[];
}

const CLASS_ROOT = "stepbar";

const Stepbar: React.FC<StepbarProps> = ({
  showTitlesFrom,
  steps,
  label = "krok",
  className,
  ...other
}) => {
  const currentItemIndex = steps.findIndex((step) => {
    return step.isCurrent;
  });

  const GetStepContent = (
    step: StepbarStep,
    index: number,
  ): React.ReactElement => {
    const fullTitle = `${index + 1}. ${step.title}`;
    return index < currentItemIndex ? (
      <a
        {...{
          href: step.href,
          className: cx(`${CLASS_ROOT}__link`, {
            [`${CLASS_ROOT}__title-${showTitlesFrom}`]: showTitlesFrom,
          }),
        }}
      >
        {fullTitle}
      </a>
    ) : (
      <span
        aria-current={index === currentItemIndex ? "step" : undefined}
        className={showTitlesFrom ? `stepbar__title-${showTitlesFrom}` : ""}
      >
        {fullTitle}
      </span>
    );
  };

  return (
    <nav
      className={cx(
        CLASS_ROOT,
        {
          [`${CLASS_ROOT}--wide-${showTitlesFrom}`]: showTitlesFrom,
        },
        className,
      )}
      aria-label={label}
      {...other}
    >
      <ol className={`${CLASS_ROOT}__list`}>
        {steps.map((step, index) => {
          return (
            <li
              key={index.toString()}
              className={cx(`${CLASS_ROOT}__item`, {
                [`${CLASS_ROOT}__item--current`]: index === currentItemIndex,
              })}
            >
              {GetStepContent(step, index)}
            </li>
          );
        })}
      </ol>
    </nav>
  );
};

Stepbar.displayName = "Stepbar";

export { Stepbar };
