import React, { cloneElement, type ReactElement } from "react";
import { Chip as MUIChip, type ChipProps as MUIChipProps } from "@mui/material";

import { Icon, type IconProps } from "../icon/Icon";
import type { AvatarProps } from "../avatar/Avatar";
import { twMerge } from "../../../tailwind.config";
import { useChipStyles } from "./Chip.styles";

export interface ChipProps
  extends Omit<
    MUIChipProps,
    "color" | "clickable" | "classes" | "size" | "variant" | "className"
  > {
  icon?: ReactElement<IconProps> | ReactElement;
  avatar?: ReactElement<AvatarProps>;
  size?: "28" | "20";
  ESCAPE_className?: string;
}

export function Chip({
  avatar = undefined,
  icon = undefined,
  disabled = false,
  size = "28",
  ESCAPE_className,
  ...restProps
}: ChipProps) {
  const { iconSvg, deleteIconSvg, ...classes } = useChipStyles(size);

  return (
    <MUIChip
      avatar={
        avatar && (
          <div>
            {cloneElement(avatar, {
              size: size === "28" ? 20 : 16,
              ...avatar.props,
            })}
          </div>
        )
      }
      icon={
        icon && (
          <div>
            {cloneElement(icon, {
              weight: "medium",
              color: "current",
              ESCAPE_className: twMerge(iconSvg, icon.props?.ESCAPE_className),
              ...icon.props,
            })}
          </div>
        )
      }
      clickable={false}
      classes={{ ...classes, root: twMerge(classes.root, ESCAPE_className) }}
      disabled={disabled}
      tabIndex={disabled ? undefined : 0}
      deleteIcon={
        <div>
          <Icon
            name="xmark"
            weight="bold"
            size="12"
            ESCAPE_className={deleteIconSvg}
          />
        </div>
      }
      aria-disabled={disabled}
      {...restProps}
    />
  );
}
