import * as React from 'react';
import { ValidationRule, Validation, ValidationState } from '../../models/Validation';
import { Colors } from '../../models/colors';
import { CommonInputProps } from '../../containers/common-input/CommonInput';
import { TooltipProps } from '../../containers/tooltip/Tooltip';
import TooltipOne from '../../components/tooltips/tooltip-one/TooltipOne';
import CommonInputLeftDot from '../../components/common-inputs/common-input-left-dot/CommonInputLeftDot';
import { Query } from '../../models/query';

interface PasswordProps {
	name: string;
	label?: string;
	type?: string;
	validationState?: Validation;
	placeholder?: string;
	validationRules?: Array<ValidationRule>;
	required?: boolean;
	palette?: Colors;
	tooltipContent?: string;
	automationName?: string;
	value?: string;
	input?: React.ReactElement<CommonInputProps>;
	tooltip?: React.ReactElement<TooltipProps>;
	notifyValidity?: (name: string, state: ValidationState, errorMessage?: string) => void;
	onChange?: (name: string, value: string) => void;
	translator?: Function;
	checkIfTranslateExist?: Function;
	query?: Query;
}

interface PasswordState {
	show: boolean;
}

export default class Password extends React.PureComponent<PasswordProps, PasswordState> {
	constructor(props: PasswordProps) {
		super(props);
		this.state = {
			show: false
		};
	}

	toggleShowHide = () => {
		this.setState({
			show: !this.state.show
		});
	};

	render() {
		const name = this.props.name || 'password';
		let errorMessage;
		let valid;
		let tooltip = null;
		if (this.props.validationState) {
			errorMessage = this.props.validationState.errorMessage;
			valid = this.props.validationState.state;
		}
		if (this.props.checkIfTranslateExist(`${this.props.name}.tooltip`)) {
			tooltip = React.cloneElement(this.props.tooltip || <TooltipOne />, {
				id: 'password',
				palette: this.props.palette,
				content: <p>{this.props.translator(`${name}.tooltip.content`)}</p>,
				translator: this.props.translator,
				query: this.props.query
			});
		}
		return React.cloneElement(this.props.input || <CommonInputLeftDot />, {
			automationName: this.props.automationName || this.props.name,
			label: this.props.label || this.props.translator(`${this.props.name}.label`),
			onChange: this.props.onChange,
			type: this.state.show ? 'text' : 'password',
			name,
			valid,
			errorMessage,
			validationRules: this.props.validationRules || [
				{
					name: 'regex',
					data: /^(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/,
					errorMessage: `${this.props.name}.regexError`
				}
			],
			required: this.props.required,
			placeholder: this.props.placeholder || '',
			notifyValidity: this.props.notifyValidity,
			toggleShowHide: this.toggleShowHide,
			show: this.state.show,
			palette: this.props.palette,
			tooltip,
			value: this.props.value,
			translator: this.props.translator
		});
	}
}
