import { Children, cloneElement, PropsWithChildren, ReactElement } from 'react'
import { GetCombinedClassesArray } from '../../../common/Helper';

export interface IErrorInputProps extends PropsWithChildren{
	error: string | null | undefined,
	errorClassses?: string | null
	children: ReactElement
} 

export default function ErrorInput(props: PropsWithChildren<IErrorInputProps>) {
	return (props.children &&
		Children.map(
			props.children, 
			(child: ReactElement) =>
			cloneElement(child, { className: CombineClasse(child.props.className, HasError(props.error), props.errorClassses)})
			// child
		)
	)

	// try{
	// 	return (
	// 		Children.map(
	// 			props.children, 
	// 			(child: ReactElement) =>
	// 			// React.cloneElement(child, { className: CombineClasse(child.props.className, HasError(props.error ?? ''), props.errorClassses)})
	// 			child
	// 		)
	// 	)
	// }	catch (ex) {
	// 	console.log('exception');
	// 	console.log(ex);
	// 	return (
	// 		<>
	// 			<h2>exception</h2>
	// 			<h2>{JSON.stringify(ex)}</h2>
	// 		</>
	// 	)
	// }
}

function CombineClasse(childClasses: Array<string>, hasError: boolean, externalErrorClasses?: string | null){
	if (!hasError) return childClasses;
	// GetCombinedClassesArray(child.props.className, (props.errorClassses ?? '') + HasError(props.error) ? (' is-danger')
	const externalErrorClassesTrimed = externalErrorClasses?.trim() ?? '';
	// const classesWithError = externalErrorClassesTrimed + (!hasError ? '' : ((externalErrorClassesTrimed.length > 0 ? ' ' : '') + 'is-danger'));
	const classesWithError = externalErrorClassesTrimed + (!hasError ? '' : ((externalErrorClassesTrimed.length > 0 ? ' ' : '') + 'is-invalid'));
	return GetCombinedClassesArray(childClasses, classesWithError);
}

export function HasError(error: string | undefined | null) {
	return error != undefined && error != null && error.length > 0;
}