import * as React from 'react';
import { TooltipProps } from '../../containers/tooltip/Tooltip';
import { legendWrapperStyle, legendTooltip, legendStyle } from './fieldset.style';
import TooltipOne from '../tooltips/tooltip-one/TooltipOne';
import { Query } from '../../models/query';

interface FieldsetProps {
	title?: string;
	tooltip?: React.ReactElement<TooltipProps>;
	[key: string]: any;
	translator?: Function;
	checkIfTranslateExist?: Function;
	query?: Query;
}

class Fieldset extends React.PureComponent<FieldsetProps> {
	render() {
		let tooltip = null;
		const childrenWithProps = React.Children.map(this.props.children, (child: any) => {
			return React.cloneElement(child, {
				...this.props,
				value: this.props.application[child.props.name],
				validationState: this.props.validations[child.props.name],
				serverErrors: (this.props.serverErrors || {})[child.props.name]
			});
		});

		if (
			this.props.checkIfTranslateExist(`${this.props.templateName}.${this.props.title}.tooltip`)
		) {
			tooltip = React.cloneElement(this.props.tooltip || <TooltipOne />, {
				id: this.props.title,
				palette: this.props.palette,
				content: this.props.translator(
					`${this.props.templateName}.${this.props.title}.tooltip.content`
				),
				translator: this.props.translator
			});
		}
		return (
			<fieldset>
				{this.props.title && (
					<div className={legendWrapperStyle}>
						<div className={legendTooltip}>
							<legend className={legendStyle(this.props.palette)}>
								{this.props.translator(`${this.props.templateName}.${this.props.title}.legend`)}
							</legend>
							{tooltip && tooltip}
						</div>
					</div>
				)}
				{childrenWithProps}
			</fieldset>
		);
	}
}

export default Fieldset;
