/**
 * TEAM: frontend_infra
 * @flow
 */

import * as React from "react";
import {StyleSheet, css} from "aphrodite";
import Text from "../Text";
import Tooltip from "../Tooltip";
import colors from "../colors";
import type {StatusIntent} from "../Status";
import Badge, {DOT_BADGE_SIZE} from "../Badge";
import {whitespaceSizeConstants} from "../styles/whitespace";

type Props = {|
  /** The text value */
  +value: ?(string | number),
  /** Determines the color of the status indicator */
  +status?: StatusIntent | null,
  /** The text of the (optional) tooltip */
  +tooltipText?: ?string,
|};

export default function TextCellWithBadge({
  value,
  status = null,
  tooltipText,
}: Props): React.Element<"div"> {
  const text = tooltipText ? (
    <Tooltip placement="bottom" overlay={<span>{tooltipText}</span>}>
      <TextContent value={value} hasTooltip={true} />
    </Tooltip>
  ) : (
    <TextContent value={value} />
  );
  return (
    <div className={css(styles.container)}>
      <div className={css(styles.badgeContainer)}>
        {status ? <Badge intent={status} value={true} /> : null}
      </div>
      {text}
    </div>
  );
}

function TextContent({
  value,
  hasTooltip = false,
}: {
  +value: ?(string | number),
  +hasTooltip?: boolean,
  ...
}) {
  return value == null ? null : (
    <div className={css(hasTooltip && styles.tooltipBorder)}>
      <Text
        overflow="hidden"
        textOverflow="ellipsis"
        whiteSpace="nowrap"
        color="grey40"
      >
        {value}
      </Text>
    </div>
  );
}

const styles = StyleSheet.create({
  container: {
    display: "inline-flex",
    alignItems: "center",
  },
  badgeContainer: {
    marginRight: whitespaceSizeConstants.s,
    minWidth: DOT_BADGE_SIZE,
  },
  tooltipBorder: {
    display: "flex",
    borderBottom: `1px dashed ${colors.grey40}`,
  },
});
