import React from "react";
import type { AutocompleteGetTagProps } from "@mui/material";
import { twJoin } from "tailwind-merge";

import { ChipContainer } from "./ChipContainer";
import SelectPlaceholder from "./SelectPlaceholder";
import { GroupedSelectOption, SelectOption, SelectProps } from "./types";
import { fetchItemLabel } from "./fetchItemLabel";

type Props = {
  selected: string | string[];
  getTagProps?: AutocompleteGetTagProps;
} & Pick<SelectProps, "placeholder" | "options" | "multiple" | "height">;

export const RenderedValue: React.FC<Props> = ({
  selected,
  placeholder,
  options,
  multiple,
  height,
  getTagProps,
}) => {
  const optionsAreGrouped = "options" in (options?.[0] ?? {});
  let optionsToRender = options;
  const className = twJoin(
    "px-6 overflow-hidden text-ellipsis whitespace-nowrap text-N700",
    height === "40" && "py-4"
  );

  if (optionsAreGrouped) {
    optionsToRender = options.flatMap(
      (option) => (option as GroupedSelectOption).options
    );
  }

  if (multiple) {
    if (selected.length > 0) {
      return (
        <ChipContainer
          getTagProps={getTagProps}
          height={height === "40" ? "28" : "20"}
          selected={selected as string[]}
          options={optionsToRender as SelectOption[]}
        />
      );
    } else {
      return (
        <div className={className}>
          <SelectPlaceholder>{placeholder}</SelectPlaceholder>
        </div>
      );
    }
  }

  const label = fetchItemLabel(
    optionsToRender as SelectOption[],
    selected as string
  );

  return (
    <div className={className}>
      {label.length !== 0 ? (
        label
      ) : (
        <SelectPlaceholder>{placeholder}</SelectPlaceholder>
      )}
    </div>
  );
};
