import React, { Component } from 'react';

import PaymentList from 'components/PaymentList'; 
import EntityStatus from 'components/EntityStatus';
import ExchangeRateFormFields, { exchangeRateFields, validateExchangeRate } 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';

import Attachments from 'lib/attachment';
import Notifications from 'lib/notification';
import Tags from 'lib/tag';

import images from 'constants/images';

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 id = valueOf("id");
		let fieldProps = { disabled, i18n };

 		return (
			<div className={ this.props.className }>
                <Tabs className="mb20">
                    <Tab title={ intl.formatMessage(messages.tabPayment) } className="container-max-900 form" titleDecorator={ <ErrorBubble errors={ errors } fields={ ["name", "dueDate", "amount"] }/> }>

                    	<div className="row row-margin-10">
                    		<div className="col-md-5">
								{ this.renderDateField("dueDate", intl.formatMessage(messages.dueDate), fieldProps) }
								<EntityStatus
									className="pv10"
									status={ valueOf("status") }
									dueDate={ valueOf("dueDate") }
									onStatusChange={ onChangeHandler("status", v => v) }
									paymentDate={ valueOf("paymentDate") }
									onPaymentDateChange={ onChangeHandler("paymentDate", s => s) }
									i18n={ i18n }
									/>
                    		</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>
                    </Tab>
                    <Tab title={ intl.formatMessage(messages.tabCurrency) } className="container-max-900 form" titleDecorator={ <ErrorBubble errors={ errors } fields={ exchangeRateFields }/> }>
                        <ExchangeRateFormFields 
                            form={ this } 
                            fieldProps={ fieldProps } 
                            intl={ intl } 
                            valueOf={ valueOf } 
                            onChangeHandler={ onChangeHandler } 
                            disabled={ disabled } 
                            unitCurrency={ unit.currency } 
                            unitCurrencySymbol={ unit.currencySymbol } 
                            dateField="incomeDate" 
                            />
                    </Tab>
                    <Tab title={ intl.formatMessage(messages.tabNotifications) } className="container-max-900 form" disabled={ !id }>
	                    <Notifications 
	                        className="pv10"
	                        unitId={ unitId } 
	                        objectType="paymentMade" 
	                        objectId={ id }
	                        disabled={ !id }
	                        imageUrls={ { google: images.googleCalendarLogo } }
	                        />
                    </Tab>
                    <Tab title={ intl.formatMessage(messages.tabAttachments) } className="container-max-900 form" disabled={ !id }>
	                    <Attachments 
	                        className="pv10"
	                        unitId={ unitId } 
	                        objectType="paymentMade" 
	                        objectId={ id }
	                        disabled={ !id }
	                        />
                    </Tab>
               	</Tabs>

			</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.dueDate)) {
			error({ field: 'dueDate', code: 'common.validation.requiredField' });
			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;
		}

		if (item.paid && !validator.required(item.paymentDate)) {
			error({ field: 'paymentDate', code: 'common.validation.requiredField' });
			valid = false;
		}

        if (!validateExchangeRate(item, error)) {
            valid = false;
        }

		return valid;
	}
});
