import * as React from 'react';

type InputValueType = any;

interface IInputProps {
    value?: InputValueType,
    onChange?:  (event: Event) => void;
}

interface IInputState {
    value: InputValueType,
}

export const createInput = (WrappedComponent: any) => {
    return class extends React.Component<IInputProps, IInputState> {
        constructor(props: IInputProps) {
            super(props);
            this.state = {
                value: this.props.value || '',
            };
        }

        public static getDerivedStateFromProps(nextProps: IInputProps, prevState: IInputProps) {
            return (nextProps.value !== prevState.value)
                ? { value: nextProps.value }
                : null;
        }

        private handleChange = (event: Event) => {
            const { onChange } = this.props;
            const el = event.target as HTMLInputElement;

            if (onChange) {
                onChange(event);
            }

            this.setState({
                value: el.value,
            })
        };

        public render() {
            const { value } = this.state;

            return <WrappedComponent
                {...this.props}
                value={value}
                onChange={this.handleChange}
            />;
        }
    }
};
