import React, { Component } from 'react';
import { Form } from '~comp/reduxForm';
import { Dialogue } from 'nixplay-ui-kit';
import { connect } from 'react-redux';
import { submit, isSubmitting, isValid, reset } from 'redux-form';
import PropTypes from 'prop-types';

import i18n from '~/locale/i18n';


export class ModalFormComponent extends Component {
	static propTypes = {
		children: PropTypes.any,
		form: PropTypes.string.isRequired,
		onCancel: PropTypes.func.isRequired,
		submit: PropTypes.func.isRequired,
		reset: PropTypes.func.isRequired,
		submitting: PropTypes.bool.isRequired,
		valid: PropTypes.bool.isRequired,
		resetOnOpen: PropTypes.bool,

		cancelText: PropTypes.string,
		submitText: PropTypes.string,
		submitColor: PropTypes.string,
		withClose: PropTypes.bool,
		withLoadingText: PropTypes.bool,
		loadingText: PropTypes.string,
	};

	static defaultProps = {
		children: {},
		cancelText: '',
		submitText: '',
		submitColor: 'blue',
		withClose: false,
		withLoadingText: true,
		loadingText: '',
		resetOnOpen: true,
	};

	constructor(props) {
		super(props);

		this.setRef = this.setRef.bind(this);
		this.reset = () => { this.props.reset(); };
	}

	setRef(ref) {
		this.modal = ref;
		this.open = () => {
			if (this.props.resetOnOpen) this.reset();
			if (this.modal) this.modal.open();
		};
		this.close = (callback) => this.modal && this.modal.close(callback);
	}

	render() {
		const {
			onCancel,
			submit: submitFn,
			cancelText,
			submitText,
			submitColor,
			valid,
			submitting,
			children,
			withLoadingText,
			loadingText,
			...others
		} = this.props;

		const cText = cancelText || i18n.t('common.cancel');
		const sText = submitText || i18n.t('common.submit');

		return (
			<Form
				{...others}
			>
				<Dialogue
					ref={this.setRef}
					onRequestClose={onCancel}
					loading={submitting}
					withClose={this.props.withClose}
					withText={withLoadingText}
					text={withLoadingText ? loadingText || i18n.t('common.loading') : undefined}
				>
					{children}
					<Dialogue.Action onPress={onCancel}>{cText}</Dialogue.Action>
					<Dialogue.Action
						onPress={submitFn}
						color={submitColor}
						disabled={!valid}
					>
						{sText}
					</Dialogue.Action>
				</Dialogue>
			</Form>
		);
	}
}

const mapStateToProps = (state, ownProps) => {
	const { form } = ownProps;
	return {
		submitting: isSubmitting(form)(state),
		valid: isValid(form)(state),
	};
};

const mapActionsToProps = (dispatch, ownProps) => {
	const { form } = ownProps;
	return {
		submit() {
			dispatch(submit(form));
		},
		reset() {
			dispatch(reset(form));
		},
	};
};

export const ModalForm = connect(
	mapStateToProps,
	mapActionsToProps,
	null,
	{ forwardRef: true },
)(ModalFormComponent);
