import React, { ReactElement, cloneElement } from "react";
import type { AutocompleteGetTagProps } from "@mui/material";

import { Chip } from "../chip/Chip";
import { Icon } from "../icon/Icon";
import type { SelectOption } from "./types";
import { fetchItemLabel } from "./fetchItemLabel";

export interface ChipContainerProps {
  selected: string[];
  options: SelectOption[];
  height: "28" | "20";
  getTagProps?: AutocompleteGetTagProps;
}

export const ChipContainer = ({
  selected,
  options,
  height,
  getTagProps,
}: ChipContainerProps) => (
  <div className="flex max-w-full flex-wrap gap-6">
    {selected.map((value, index) => {
      const option = options.find(
        (option) => option.value === value
      ) as SelectOption;

      let icon: ReactElement | undefined;
      let avatar: ReactElement | undefined;

      if (option?.showIconInChip) {
        if (typeof option?.icon === "string") {
          icon = <Icon name={option?.icon} />;
        } else if (option?.icon !== undefined) {
          avatar = cloneElement(option?.icon, {
            size: height === "28" ? 20 : 16,
            ...option?.icon?.props,
          });
        }
      }

      return (
        <Chip
          {...getTagProps?.({ index })}
          key={value}
          icon={icon}
          avatar={avatar}
          size={height}
          label={fetchItemLabel(options, value)}
        />
      );
    })}
  </div>
);
