/**
 * TEAM: frontend_infra
 * @flow strict
 */
/* eslint-disable react/prefer-stateless-function */

import * as React from "react";

import {StyleSheet, css, type SheetEntry} from "aphrodite";
import {margin} from "./styles/whitespace";
import {include} from "./styles";

import Icon from "./Icon";
import type {IconNames} from "./Icon";
import type {Color} from "./colors";
import Text from "./Text";
import Group from "./Group";

type Intent = "warning" | "error";

type Props = {|
  /** Message that appears below input field when showError is true. Strings will be preceded by an icon. */
  +errorText: string | React.Node,
  /** Whether or not the error message is displayed */
  +showError?: boolean,
  /** Defines the visual style which conveys the level of importance / urgency to the user. */
  +intent?: Intent,
  +children?: React.Node,
|};

/**
 * @short Renders error text relating to an input below the input; if not error is shown, the spacing it would have taken up is maintained (to avoid UX jitter).
 * @category Data Entry
 * @brandStatus V2
 * @status Stable
 */
export default function InputValidationMessage({
  errorText,
  showError = false,
  children,
  intent = "error",
}: Props): React.Element<"div"> {
  const iconName = getIconName(intent);
  const iconColor = getIconColor(intent);
  const textColor = getTextColor(intent);
  // Empty arrays or strings are sometimes passed to errorText. We don't want to show an icon with no text to follow.
  const showIcon =
    typeof errorText === "string" || Array.isArray(errorText)
      ? errorText.length > 0
      : true;
  return (
    <div>
      {children}
      {showError && showIcon ? (
        <div
          className={css(
            inputValidationMessageStyles.inputValidationMessage,
            true && inputValidationMessageStyles.redesign
          )}
        >
          <Group flexWrap="nowrap" alignItems="center">
            <Icon iconName={iconName} color={iconColor} />
            <Text color={textColor}>{errorText}</Text>
          </Group>
        </div>
      ) : null}
    </div>
  );
}

const getIconName = (intent: Intent): IconNames => {
  if (intent === "warning") {
    return "attention";
  }
  return "customsFail";
};

const getIconColor = (intent: Intent): Color => {
  if (intent === "warning") {
    return "orange30";
  }
  return "red40";
};

const getTextColor = (intent: Intent): Color => {
  if (intent === "warning") {
    return "orange40";
  }
  return "red40";
};

export const inputValidationMessageStyles: {|
  inputValidationMessage: SheetEntry,
  redesign: SheetEntry,
|} = StyleSheet.create({
  inputValidationMessage: {
    fontSize: "13px",
  },
  redesign: {
    ...include(margin.t.xs),
    fontWeight: 500,
  },
});
