import React, { Component } from 'react';

import PaymentList from 'components/PaymentList'; 
import EntityStatus from 'components/EntityStatus';
import ExchangeRateFormFields from 'components/ExchangeRateFormFields';
import { AbstractForm, ActivityIndicator, ButtonBar, Button, Alert, Tabs, Tab, ErrorBubble } from 'lib/components';
import Toast from 'components/Toast';

import form from 'lib/form';
import validator from 'lib/validator';
import { injectIntl } from 'react-intl';
import messages from './messages';

import backendRequest from 'lib/backend';

class PaymentItemForm extends AbstractForm {

	constructor(props) {
		super(props);

		this.fetchPayments = this.fetchPayments.bind(this);
	}


	async fetchPayments() {
        let unitId = this.props.unitId;

        let payments = [];
        try {
            let response = await backendRequest(`/api/${unitId}/payments/categories`, "GET");
            payments = response.body;
        } catch(e) {
            console.error(e);
        }
        return payments;
	}


	render() {
		let { valueOf, onChangeHandler, i18n, intl, status, disabled, unitId, children, errors, unit = {}, paymentReadOnly } = this.props;
		let paid = valueOf("paid", false);
		let fieldProps = { disabled, i18n };
		let frequency = [
			{ value: "M", label: intl.formatMessage(messages.monthly) },
			{ value: "w", label: intl.formatMessage(messages.weekly) },
			{ value: "Q", label: intl.formatMessage(messages.quarterly) },
			{ value: "y", label: intl.formatMessage(messages.yearly) },
			{ value: "d", label: intl.formatMessage(messages.daily) }
		];

 		return (
			<div className={ `form ${this.props.className}` }>
            	<div className="row row-margin-10">
            		<div className="col-md-5">
						{ this.renderDateField("dateFrom", intl.formatMessage(messages.dateFrom), fieldProps) }
						{ this.renderNumericField("cycles", intl.formatMessage(messages.cycles), fieldProps) }
						{ this.renderToggleButtons("frequency", intl.formatMessage(messages.frequency), frequency, fieldProps) }
            		</div>
            		<div className="col-md-2"/>
            		<div className="col-md-5">
						{ this.renderSelectModal("payment", intl.formatMessage(messages.category), {
							disabled: disabled || paymentReadOnly,
							fetchData: this.fetchPayments,
							readInputValue: (v) => v ? v.name : "",
							renderList: (items, onChange, hide) => <PaymentList 
																items={ items }
																onDetailClick={ (id, payment) => {
																	this.props.setValues(null, {
																		payment: payment,
																		currencySymbol: payment.currencySymbol,
																		currency: payment.currency
																	});
																	hide();
																} }
																/>
						}) }
            		</div>
            	</div>

				{ this.renderField("name", intl.formatMessage(messages.name), { ...fieldProps, className: "big" }) }

				{ this.renderTextArea("note", intl.formatMessage(messages.description), fieldProps) }

				<div className="row row-margin-10">
            		<div className="col-md-7"/>
            		<div className="col-md-5">
            			{ this.renderMoneyField("amount", intl.formatMessage(messages.amount), valueOf("currencySymbol"), valueOf("currency"), { ...fieldProps, className: "big" }) }
            		</div>
				</div>

			</div>
		);
	}


}


export default form(injectIntl(PaymentItemForm), {
	onValidationFailed: Toast.validationFailed,
	validate: (item, error) => {
		let valid = true;

		if (!validator.required(item.name)) {
			error({ field: 'name', code: 'common.validation.requiredField' });
			valid = false;
		}
		if (!validator.required(item.currencySymbol)) {
			error({ field: 'currencySymbol', code: 'common.validation.requiredField' });
			valid = false;
		}
		if (!validator.required(item.currency)) {
			error({ field: 'currency', code: 'common.validation.requiredField' });
			valid = false;
		}
		if (!validator.required(item.dateFrom)) {
			error({ field: 'dateFrom', code: 'common.validation.requiredField' });
			valid = false;
		}
		if (!validator.required(item.frequency)) {
			error({ field: 'frequency', code: 'common.validation.requiredField' });
			valid = false;
		}
		if (!validator.required(item.cycles)) {
			error({ field: 'cycles', code: 'common.validation.requiredField' });
			valid = false;
		} else if (!validator.number(item.cycles)) {
			error({ field: 'cycles', code: 'common.validation.numberField' });
			valid = false;
		}
		if (!validator.required(item.amount)) {
			error({ field: 'amount', code: 'common.validation.requiredField' });
			valid = false;
		} else if (!validator.decimal(item.amount)) {
			error({ field: 'amount', code: 'common.validation.decimalField' });
			valid = false;
		}

		return valid;
	}
});
