import * as React from 'react';
import { ValidationState, ValidationRule } from '../../models/Validation';
import { validation, validationOnInit } from '../../utils/helper';
import validationRules from '../../utils/validationRules';
import { Colors } from '../../models/colors';
import { TooltipProps } from '../tooltip/Tooltip';

const tagManager = require('react-gtm-module');

export interface RadioButtonProps {
	required?: boolean;
	name?: string;
	label?: string;
	valid?: ValidationState;
	selectedRadio?: string;
	validationRules?: Array<ValidationRule>;
	palette?: Colors;
	errorMessage?: string;
	automationName?: string;
	options?: { label: string; id: string }[];
	tooltip?: React.ReactElement<TooltipProps>;
	onChange?: (name: string, value: string) => void;
	notifyValidity?: (name: string, state: ValidationState, errorMessage?: string) => void;
	translator?: Function;
}

type RadioButtonContainer = RadioButtonProps & {
	render: (onClick: (e: any) => void) => JSX.Element;
};

class RadioButton extends React.PureComponent<RadioButtonContainer> {
	constructor(props: RadioButtonContainer) {
		super(props);
		let assignedValidationRules = Object.assign([], this.props.validationRules || []);

		if (this.props.required) {
			assignedValidationRules.unshift({ name: 'required' });
		}

		if (this.props.notifyValidity) {
			let { name, state, errorMessage } = validationOnInit(
				validationRules,
				assignedValidationRules,
				this.props.name,
				props.selectedRadio,
				this.props.translator
			);
			this.props.notifyValidity(name, state, errorMessage);
		}
	}

	onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		tagManager.dataLayer({
			dataLayer: {
				event: 'on-change',
				'input-name': name
			}
		});
		let assignedValidationRules = Object.assign([], this.props.validationRules || []);
		let { state, errorMessage } = validation(
			validationRules,
			assignedValidationRules,
			e.target.id,
			this.props.name,
			this.props.translator
		);
		if (this.props.notifyValidity) {
			this.props.notifyValidity(this.props.name, state, errorMessage);
		}
		this.props.onChange(this.props.name, e.target.id);
	};

	render() {
		return this.props.render(this.onChange);
	}
}

export default RadioButton;
