"use client";

import type { ReactNode, ReactElement, RefAttributes } from "react";
import { cloneElement, Children } from "react";
import classNames from "classnames/dedupe";
import type { DOMProps } from "../../types/dom";
import { Box } from "../Box";

export type BreadcrumbItemElementType = HTMLLIElement;

export interface BreadcrumbItemProps
  extends DOMProps, RefAttributes<BreadcrumbItemElementType> {
  "aria-current"?:
    | "page"
    | "step"
    | "location"
    | "date"
    | "time"
    | boolean
    | "true"
    | "false";
  isDisabled?: boolean;
  isCurrent?: boolean;
  separator?: ReactNode;
  className?: string;
  children: ReactNode;
}

const BreadcrumbItem = ({ ref, ...props }: BreadcrumbItemProps) => {
  const {
    isDisabled = false,
    isCurrent = false,
    "aria-current": ariaCurrent = "page",
    children,
    separator = (
      <Box className="mobius-breadcrumb__separator" aria-hidden="true">
        {">"}
      </Box>
    ),
    ...otherProps
  } = props;
  const { itemProps } = {
    itemProps: {
      "aria-current": isCurrent ? ariaCurrent : undefined,
      "aria-disabled": isDisabled || isCurrent,
      ...otherProps,
    },
  };

  // Reshape class name and apply to outer element
  const classes = classNames(
    "mobius",
    "mobius-breadcrumb__item",
    props.className,
  );

  const child: ReactElement =
    typeof children === "string" ? (
      <span {...itemProps}>{children}</span>
    ) : (
      (Children.only(children) as ReactElement)
    );

  return (
    <li className={classes}>
      {cloneElement(child, {
        ...(child.props as Record<string, unknown>),
        ...itemProps,
        ref,
      } as Record<string, unknown>)}
      {!props.isCurrent && separator}
    </li>
  );
};

BreadcrumbItem.displayName = "BreadcrumbItem";
export { BreadcrumbItem };
