import { cloneElement, forwardRef, memo } from "react";

import { Link } from "../../link";
import { CrumbText, Crumb as StyledCrumb, StyledCrumbButton } from "../breadcrumbs.styled";

import type { CrumbProps } from "./crumb-props";

const BaseCrumbComponent = forwardRef<
  HTMLAnchorElement | HTMLButtonElement,
  Omit<CrumbProps, "divider">
>(
  // eslint-disable-next-line max-lines-per-function
  ({ crumb, isLast, iconPosition, ellipsis = true, ...rest }, ref) => {
    if ("linkElement" in crumb) {
      return cloneElement(
        crumb.linkElement,
        {
          style: { ...crumb.linkElement.props.style, width: "100%", display: "block" },
          ...rest,
          ref: ref as React.ForwardedRef<HTMLAnchorElement>,
        },
        <StyledCrumb iconEnd={iconPosition === "end" && Boolean(crumb.Icon)}>
          {crumb.Icon}
          {crumb.linkElement.props.children && (
            <CrumbText variant="body4" isLast={isLast} ellipsis={ellipsis}>
              {crumb.linkElement.props.children}
            </CrumbText>
          )}
        </StyledCrumb>
      );
    }

    if ("href" in crumb) {
      return (
        <Link
          ref={ref as React.ForwardedRef<HTMLAnchorElement>}
          {...crumb.linkProps}
          href={crumb.href}
          css={{ width: "100%" }}
          {...rest}
          data-crumb-item-type={crumb.Icon ? "icon" : "text"}
        >
          <StyledCrumb iconEnd={iconPosition === "end" && Boolean(crumb.Icon)}>
            {crumb.Icon}
            {crumb.label && (
              <CrumbText variant="body4" isLast={isLast} ellipsis={ellipsis}>
                {crumb.label}
              </CrumbText>
            )}
          </StyledCrumb>
        </Link>
      );
    }

    if ("onClick" in crumb) {
      return (
        <StyledCrumbButton
          type="button"
          ref={ref as React.ForwardedRef<HTMLButtonElement>}
          {...crumb.buttonProps}
          {...rest}
          onClick={crumb.onClick}
          data-crumb-item-type={crumb.Icon ? "icon" : "text"}
        >
          <StyledCrumb iconEnd={iconPosition === "end" && Boolean(crumb.Icon)} as="span">
            {crumb.Icon}
            {crumb.label && (
              <CrumbText variant="body4" isLast={isLast} ellipsis={ellipsis}>
                {crumb.label}
              </CrumbText>
            )}
          </StyledCrumb>
        </StyledCrumbButton>
      );
    }

    return (
      <StyledCrumb iconEnd={iconPosition === "end" && Boolean(crumb.Icon)} {...rest}>
        {crumb.Icon}
        <CrumbText variant="body4" isLast={isLast} ellipsis={ellipsis}>
          {crumb.label}
        </CrumbText>
      </StyledCrumb>
    );
  }
);

BaseCrumbComponent.displayName = "BaseCrumb";

export const BaseCrumb = memo(BaseCrumbComponent);
