import * as React from 'react';
import { CommonInputProps } from '../../../containers/common-input/CommonInput';
import { TooltipProps } from '../../../containers/tooltip/Tooltip';
import Input from '../common-input-left-dot/inner-comps/dropdownList/inner-comps/input/Input';

type InputWithCurrencyProps = CommonInputProps & {
	tooltip?: React.ReactElement<TooltipProps>;
	input?: React.ReactElement<CommonInputProps>;
	currency: string;
	translator?: Function;
};

let currencyFormatter = require('currency-formatter');

const InputWithCurrency = (props: InputWithCurrencyProps) => {
	let name = props.name;
	let currency = props.currency;
	let value = props.value
		? currencyFormatter.format(props.value, { code: currency, precision: 0 })
		: null;
	let onChange = (name: string, value: string) => {
		let unformatted = currencyFormatter.unformat(value, { code: currency, decimal: true });
		props.onChange(name, unformatted);
	};

	let onKeyDown = (value: string, e: React.KeyboardEvent<HTMLInputElement>) => {
		let unformatted = currencyFormatter.unformat(value, {
			code: currency,
			decimal: true
		});
		if (props.onKeyDown) {
			props.onKeyDown(unformatted, e);
		}
	};

	let onBlur = (value: string) => {
		let unformatted = currencyFormatter.unformat(value, { code: currency, decimal: true });
		if (props.onBlur) {
			props.onBlur(unformatted);
		}
	};
	return React.cloneElement(props.input || <Input />, {
		automationName: props.automationName || props.name,
		label: props.label || props.translator(`${props.name}.label`),
		onChange,
		type: 'text',
		name,
		valid: props.valid,
		errorMessage: props.errorMessage,
		validationRules: props.validationRules,
		placeholder: props.placeholder || '',
		notifyValidity: props.notifyValidity,
		tooltip: props.tooltip,
		palette: props.palette,
		value,
		required: props.required,
		onKeyDown,
		onBlur,
		translator: props.translator
	});
};

export default InputWithCurrency;
