import React, { FocusEventHandler, FunctionComponent, KeyboardEventHandler, ReactNode } from "react";
import { Button } from "../Button";
import { createFormattedNumberInputHandler, formatNumber, positiveNumericFieldHandler } from "../../utils/handlers";

import "./styles.scss";

interface ICurrencyInputProps {
  label?: ReactNode;
  subLabels?: string[];
  currencyLogo?: string;
  currencySymbol?: string;
  value?: string;
  onChange?: (value: string) => void;
  onKeyDown?: KeyboardEventHandler<HTMLInputElement>;
  onBlur?: FocusEventHandler<HTMLInputElement>;
  onMax?: () => void;
  placeholder?: string;
  disabled?: boolean;
  warning?: string | ReactNode;
  error?: string;
}

const CurrencyInput: FunctionComponent<ICurrencyInputProps> = (props) => {
  const {
    label,
    error,
    subLabels = [],
    currencyLogo = "",
    currencySymbol = "",
    value = "",
    onChange,
    onKeyDown,
    onBlur,
    onMax,
    placeholder = "",
    disabled = false,
    warning,
  } = props;

  const inputHandler = createFormattedNumberInputHandler(
    value,
    (pureValue) => onChange && positiveNumericFieldHandler(pureValue, onChange)
  );

  const inputContainer = `c-currency-input ${ (disabled && "c-currency-input--disabled") || ""}`;

  return (
    <div className={inputContainer}>
      {label && <div className="c-currency-input__label">{label}</div>}
      <div className="c-currency-input__input-container">
        <div className="c-currency-input__input-control-container">
          {subLabels.length > 0 && (
            <div className="c-currency-input__input-sub-labels">
              {subLabels.map((label, index) => (
                <div key={label + index} className="c-currency-input__input-sub-label">
                  {label}
                </div>
              ))}
            </div>
          )}
          <div className="c-currency-input__input-control">
            <div className="c-currency-input__input-currency">
              {currencyLogo && <img alt="coin logo" className="c-currency-input__input-currency-logo" src={currencyLogo} />}
              {currencySymbol}
            </div>
            <input
              onChange={inputHandler}
              onKeyDown={onKeyDown}
              onBlur={onBlur}
              disabled={disabled}
              placeholder={placeholder}
              className="c-currency-input__input"
              value={formatNumber(value)}
            />
          </div>
        </div>
        {onMax && (
          <div className="c-currency-input__buttons">
            <Button disabled={disabled} onClick={onMax} type="secondary" size="small">
              Max
            </Button>
          </div>
        )}
      </div>
      {error && <div className="c-currency-input__validation">{error}</div>}
      {warning && <div className="c-currency-input__warning">{warning}</div>}
    </div>
  );
};

export { CurrencyInput };
