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

import * as React from "react";
import {StyleSheet, css} from "aphrodite";
import NumberFormat from "react-number-format";
import type {TextInputProps, TextAlignment} from "./TextInput";
import InputGroupContext, {
  CENTER_INPUT,
  LEFT_INPUT,
  RIGHT_INPUT,
} from "./context/InputGroupContext";
import {getInputStyles} from "./styles/input";

export type ThousandsGroupStyle = "thousand" | "lakh" | "wan";
type Props = {|
  +value: string | number | null,
  +placeholder?: TextInputProps["placeholder"],
  +size?: TextInputProps["size"],
  +readOnly?: TextInputProps["readOnly"],
  +disabled?: TextInputProps["disabled"],
  +isPrefilled?: TextInputProps["isPrefilled"],
  +isInvalid?: TextInputProps["isInvalid"],
  +onChange: TextInputProps["onChange"],
  +textAlign?: TextAlignment,
  +format?: string,
  +mask?: string,
  +type?: TextInputProps["type"],
  +decimalSeparator?: string,
  +thousandSeparator?: string,
  +thousandsGroupStyle?: ThousandsGroupStyle,
  +decimalScale?: number,
  +fixedDecimalScale?: boolean,
  +prefix?: string,
  +suffix?: string,
|};
export default function NumberFormatInput({
  value,
  placeholder,
  onChange,
  size = "m",
  disabled = false,
  readOnly = false,
  isInvalid = false,
  isPrefilled = false,
  textAlign = "left",
  format,
  mask,
  type = "tel",
  decimalSeparator,
  thousandSeparator,
  thousandsGroupStyle,
  decimalScale,
  fixedDecimalScale,
  prefix,
  suffix,
}: Props): React.Element<"div"> {
  const inputGroupContext = React.useContext(InputGroupContext);

  const inputStyle = css(
    ...getInputStyles({
      size,
      readOnly: readOnly === "styledReadOnly" ? false : readOnly,
      disabled,
      isInvalid,
      isPrefilled,
      noPadding: false,
    }),
    inputGroupContext === CENTER_INPUT && styles.noBorders,
    inputGroupContext === LEFT_INPUT && styles.noRightBorders,
    inputGroupContext === RIGHT_INPUT && styles.noLeftBorders
  );

  return (
    <div className={css(styles.wrapper)}>
      <NumberFormat
        className={inputStyle}
        onChange={evt => onChange(evt.target.value)}
        placeholder={placeholder}
        value={value}
        readOnly={readOnly}
        disabled={disabled}
        format={format}
        mask={mask}
        type={type}
        decimalSeparator={decimalSeparator}
        thousandSeparator={thousandSeparator}
        thousandsGroupStyle={thousandsGroupStyle}
        decimalScale={decimalScale}
        fixedDecimalScale={fixedDecimalScale}
        prefix={prefix}
        suffix={suffix}
        style={{textAlign}}
      />
    </div>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    display: "flex",
    position: "relative",
  },
  noBorders: {
    borderRadius: "0px 0px 0px 0px",
  },
  noLeftBorders: {
    borderRadius: "0px 3px 3px 0px",
  },
  noRightBorders: {
    borderRadius: "3px 0px 0px 3px",
  },
});
