import React, { ReactNode } from "react";
import { Box } from "../../Box";
import { Text } from "../../Text";
import { Truncate } from "../../Truncate";
import { SelectOption, SingleSelectedOption } from "../shared/types";

interface SingleSelectSelectedProps<T extends SelectOption> {
  selectedItem: SingleSelectedOption<T>;
  placeholder: ReactNode | undefined;
  renderSelected:
    | (({
        selectedItem,
      }: {
        selectedItem: SingleSelectedOption<T>;
      }) => ReactNode)
    | undefined;
}

export function SingleSelectSelected<T extends SelectOption>({
  selectedItem,
  placeholder,
  renderSelected,
}: SingleSelectSelectedProps<T>) {
  const selectedItemLabel = selectedItem ? selectedItem.label : "";
  const isPlaceholderVisible = !selectedItem && !!placeholder;

  if (isPlaceholderVisible) {
    return (
      <Text as="span" className="text-gray-600">
        {placeholder}
      </Text>
    );
  }

  return renderSelected ? (
    <Box>{renderSelected({ selectedItem })}</Box>
  ) : (
    <Truncate lines={1} className="text-left">
      <Text as="span" className="text-gray-800">
        {selectedItemLabel}
      </Text>
    </Truncate>
  );
}
