import { css } from "@emotion/react";
import { useMemo } from "react";

import type { TextProps } from "@phoenix/components";
import { Flex, Icon, Icons, Text } from "@phoenix/components";
import type { TextColorValue } from "@phoenix/components/core/types/style";
import { latencyMsFormatter } from "@phoenix/utils/numberFormatUtils";
/**
 * The thresholds for the latency text color.
 * The numbers are in milliseconds.
 */
export type LatencyThresholds = {
  /**
   * The threshold for the fast latency.
   * Anything less than this is considered fast.
   */
  fast: number;
  /**
   * The threshold for the moderate latency.
   * Anything between this and the slow threshold is considered moderate. Anything greater than this is considered slow.
   */
  moderate: number;
};
export function LatencyText({
  latencyMs,
  size = "M",
  showIcon = true,
  latencyThresholds,
  color: colorProp = "text-900",
}: {
  latencyMs: number | null;
  size?: TextProps["size"];
  /**
   * The thresholds for the latency text color.
   * @default undefined
   */
  latencyThresholds?: LatencyThresholds;
  /**
   * Whether to show the clock icon.
   * @default true
   */
  showIcon?: boolean;
  /**
   * The color of the text when no latency thresholds apply.
   * @default "text-900"
   */
  color?: TextColorValue;
}) {
  const color: TextColorValue = useMemo(() => {
    if (latencyThresholds && latencyMs !== null) {
      if (latencyMs < latencyThresholds.fast) {
        return "success";
      } else if (latencyMs < latencyThresholds.moderate) {
        return "warning";
      } else {
        return "danger";
      }
    }
    return colorProp;
  }, [latencyMs, latencyThresholds, colorProp]);

  const latencyText = useMemo(() => latencyMsFormatter(latencyMs), [latencyMs]);

  return (
    // No justify-content: it would override the right-alignment a numeric
    // table cell applies to its flex children.
    <Flex
      direction="row"
      alignItems="center"
      gap="size-50"
      className="latency-text"
    >
      {showIcon ? (
        <Text color={color} size={size}>
          <Icon
            svg={<Icons.Clock />}
            css={css`
              font-size: 1.1em;
            `}
          />
        </Text>
      ) : null}
      <Text color={color} size={size} fontFamily="mono">
        {latencyText}
      </Text>
    </Flex>
  );
}
