import React, { Component } from "react";

import StatusChart from 'components/StatusChart';
import PaymentStats from 'components/PaymentStats';
import { LabeledValue } from "lib/components";

import { formatMoney, formatDate } from "lib/i18n";
import { injectIntl } from 'react-intl';
import { num } from 'utils/calc';
import { fromJS } from 'immutable';
import icons from 'constants/icons';

import messages from './messages.js';


require("./style.scss")



class PaymentReportData extends Component {


    constructor(props) {
        super(props);

        this.initData = this.initData.bind(this);
        this.selectPaymentRow = this.selectPaymentRow.bind(this);
        this.togglePaymentRow = this.togglePaymentRow.bind(this);
        this.toggleDetails = this.toggleDetails.bind(this);

        this.state = {
            data: {},
            details: {}
        };
    }


    componentWillMount() {
        this.initData(this.props.data);
    }


    componentWillReceiveProps(props) {
        if (props.data != this.props.data) {
            this.initData(props.data);
        }
    }


    initData(d) {
        if (!d) {
            d = {};
        }

        let data = fromJS(d);

        //calculate chart
        for (let i = 0; i < d.length; i++) {
            let chart = {
                draft: 0,
                active: 0,
                finished: 0,
                overdue: 0
            };

            if (Array.isArray(d[i].payments)) {
                for (let j = 0; j < d[i].payments.length; j++) {
                    let p = d[i].payments[j];
                    if (p.status) {
                        switch (p.status) {
                            case "draft":
                            case "planned":
                                chart.draft = chart.draft + p.amount;
                                break;
                            case "active":
                                chart.active = chart.active + p.amount;
                                break;
                            case "finished":
                                chart.finished = chart.finished + p.amount;
                                break;
                            case "overdue":
                                chart.overdue = chart.overdue + p.amount;
                                break;
                        }
                    }
                }

                data = data.setIn([i, "chart"], chart);
            }
        }


        this.setState({ data });
    }


    toggleDetails(data, paymentIndex, showPayments) {
        let payment = data.get(paymentIndex);
        data = data.setIn([paymentIndex, "showPayments"], showPayments);

        if (showPayments) {
            //recalculate items
            let sum = this.calculatePaymentSum(data.getIn([paymentIndex, "payments"]));
            data = data.setIn([paymentIndex, "sum"], sum);
        } else {
            //get data from properties
            let d = this.props.data;
            let p = d[paymentIndex];
            if (p && !isNaN(p.paid)) {
                data = data.setIn([paymentIndex, "sum"], p.paid);
            }
        }

        this.setState({ data });
    }


    calculatePaymentSum(payments) {
        let sum = 0;
        for (let i = 0; i < payments.size; i++) {
            let item = payments.get(i);
            if (item.get("selected")) {
                let amount = num(item.get("amount") || 0);
                sum += amount;
            }
        }
        return sum;
    }


    selectPaymentRow(data, paymentIndex, itemIndex) {
        return (e) => {
            e.stopPropagation();
            e.preventDefault();

            data = data.setIn([paymentIndex, "payments", itemIndex, "selected"], e.target.checked);
            let sum = this.calculatePaymentSum(data.getIn([paymentIndex, "payments"]));
            data = data.setIn([paymentIndex, "sum"], sum);
            this.setState({ data });
        }
    }


    togglePaymentRow(data, paymentIndex, itemIndex) {
        return (e) => {
            //e.preventDefault();

            data = data.setIn([paymentIndex, "payments", itemIndex, "selected"], !data.getIn([paymentIndex, "payments", itemIndex, "selected"]));
            let sum = this.calculatePaymentSum(data.getIn([paymentIndex, "payments"]));
            data = data.setIn([paymentIndex, "sum"], sum);
            this.setState({ data });
        }
    }


	renderPayment(data, index, i18n, intl) {
        let payment = data.get(index);
        let currency = payment.get("currencySymbol");
        let payments = payment.get("payments");

        let showPayments = payment.get("showPayments") || false;


        let rows = [];
        if (showPayments) {
            for (let i = 0; i < payments.size; i++) {
                let p = payments.get(i);
                let className = "";
                let selected = p.get("selected");

                className += selected ? " checked" : " unchecked";

                rows.push((
                    <div key={ i } className={ `flex-list-row ${className}` }>
                        <div className="content">
                            <div className="list-row-data">
                                <div className="record-type">
                                    <div className="icon">
                                        { icons.payment }
                                        <div className={`status-indicator ${p.get("status") || "planned"}`}/>
                                    </div>
                                    <div className="date">{ formatDate(p.get("date"), i18n) }</div>
                                </div>
                                <div className="main">
                                    <div className="main-value">
                                        { p.get("name") }
                                    </div>
                                    <div className="additional-info">
                                        {/* secondary.join(" | ") */}
                                    </div>
                                </div>
                                <div className="right p5">
                                    <div className="main-value">
                                        { formatMoney(p.get("amount"), currency, i18n) }
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="actions">
                            <a className="checkbox" onClick={ this.togglePaymentRow(data, index, i, selected) }>
                                <input type="checkbox" checked={ selected } readOnly={ true } />
                            </a>
                        </div>
                    </div>
                ));
            }
        }

		return (
			<div key={ payment.get("id") } className="clearfix mb30">
                <div className="">
    				<div className="pv10">
                        <h3>{ payment.get("name") }</h3>
                        <div className="row pv10">
                            <div className="col-md-6">

                                <StatusChart 
                                    data={ payment.get("chart") } 
                                    currency={ currency } 
                                    i18n={ i18n } 
                                    /> 

                            </div>
                            <div className="col-md-6">
                                <div className="col-xs-6 summary-panel p10 right">
                                    <LabeledValue label={intl.formatMessage(messages.paid) }>
                                        { formatMoney(payment.get("paid"), currency, i18n) }
                                    </LabeledValue>
                                </div>
                                <div className="col-xs-6 summary-panel p10 right">
                                    <LabeledValue label={intl.formatMessage(messages.overdue) }>
                                        { formatMoney(payment.get("overdue"), currency, i18n) }
                                    </LabeledValue>
                                </div>
                                <div className="col-xs-6 summary-panel p10 right">
                                    <LabeledValue label={ intl.formatMessage(messages.pending) }>
                                        { formatMoney(payment.get("pending"), currency, i18n) }
                                    </LabeledValue>
                                </div>
                                <div className="col-xs-6 summary-panel p10 right">
                                    <LabeledValue label={ intl.formatMessage(messages.total) } size="big">
                                        { formatMoney(payment.get("total"), currency, i18n) }
                                    </LabeledValue>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="center p10">
                        { payments && payments.size ? <button className="btn" onClick={ () => this.toggleDetails(data, index, !showPayments) }>{ intl.formatMessage(showPayments ? messages.hidePayments : messages.showPayments) }</button> : null }
                    </div>
                    { showPayments ? (<div className="">
                            { rows }
                            <div className="right">
                                <LabeledValue label={ intl.formatMessage(messages.sum) }>
                                    { formatMoney(payment.get("sum"), currency, i18n) }
                                </LabeledValue>
                            </div>
                        </div>
                    ) : null }
                </div>
			</div>
		);
	}

	render() {
		let { i18n, intl } = this.props;
        let { data } = this.state;

		let types = [];
		if (data) {
			for (let i = 0; i < data.size; i++) {
				types.push(this.renderPayment(data, i, i18n, intl));
			}
		}

		return (
			<div className="container-max-900">
				{ types }
			</div>
		);
	}

}


export default injectIntl(PaymentReportData);
