import React, { Component } from 'react';
import PropTypes from 'prop-types';

import { connect } from 'react-redux';
import { fetchSettingsAction,saveSettingsAction, selector } from './redux.js';
import { download } from 'lib/backend';

import DphSettingsForm from 'components/DphSettingsForm';
import DphParamsForm from 'components/DphParamsForm';
import { ActivityIndicator, Button, ButtonBar, DetailTitle, ToolbarButton, Toolbar, ToolbarSection, ToolbarButtons, ToolbarRow } from 'lib/components';
import Attachments from 'lib/attachment';

import { injectIntl } from 'react-intl';
import icons from 'constants/icons';

class DphReport extends Component {

	constructor(props) {
		super(props);

		this.saveSettings = this.saveSettings.bind(this);
		this.handleBack = this.handleBack.bind(this);

		this.handleDownload = this.handleDownload.bind(this);

		this.state = {};
	}


	async componentWillMount() {
		let unitId = this.props.unitId;
		await this.props.fetchSettingsAction(unitId);
		if (this.props.settings) {
			this.setState({ initialized: !!this.props.settings.id, mode: this.props.settings.id ? "params" : "settings" });
		} else {
			//TODO
		}
	} 


	handleBack() {
		this.context.router.push('/reports');
	}


	async saveSettings(params) {
		let unitId = this.props.unitId;
		try {
			await this.props.saveSettingsAction(unitId, params);
			this.setState({ mode: "params" });
		} catch (e) {
			console.error(e);
		}
	}


	handleDownload(params) {
		let reportType = this.state.reportType || "kh";
		let unitId = this.props.unitId;
		download(`/api/${unitId}/dph/${reportType}`, { params });
	}


	render() {
		let output = null;
		let { intl } = this.props;

		if (this.state.mode == "settings") {
			output = (			
				<div className="pv10">
	                <Toolbar>
	                    <ToolbarSection>
	                        <DetailTitle
	                            title="Nastavení EPO"
	                            titleIcon={ icons.settings }/>
	                    </ToolbarSection>
	                    <ToolbarButtons>
	                        <ToolbarButton 
	                            label={ intl.formatMessage({ id: "common.button.back" }) } 
	                            onClick={ () => this.state.initialized ? this.setState({ mode: "params" }) : this.context.router.push('/reports') }>
	                            <span className="icon">{ icons.back }</span>
	                        </ToolbarButton>
	                        <ToolbarButton 
								title="Uložit"
								onClick={ () => this.refs.settingsForm.submit() }>
	                            <span className="icon">{ icons.save }</span>
	                        </ToolbarButton>
	                    </ToolbarButtons>
	                    <ToolbarRow>
	                    </ToolbarRow>
	                </Toolbar>

					<DphSettingsForm
						data={ this.props.settings } 
						ref="settingsForm"
						disabled={ this.props.isSettingsPending }

						onSubmit={ this.saveSettings }
						unitId={ this.props.unitId }
						{...this.props.data}
						/>

					<ActivityIndicator show={ this.props.isSettingsPending } type="overlay"/>
				</div>
			);
		} else if (this.state.mode == "params") {
			output = (
				<div className="pv10">
	                <Toolbar>
	                    <ToolbarSection>
	                        <DetailTitle
	                            title="EPO - DPH"
	                            titleIcon={ icons.reports }/>
	                    </ToolbarSection>
	                    <ToolbarButtons>
	                        <ToolbarButton 
	                            label={ intl.formatMessage({ id: "common.button.back" }) } 
	                            onClick={ this.handleBack }>
	                            <span className="icon">{ icons.back }</span>
	                        </ToolbarButton>
	                        <ToolbarButton 
	                            label="Nastavení"
	                            onClick={ () => this.setState({ mode: "settings" }) }>
	                            <span className="icon">{ icons.settings }</span>
	                        </ToolbarButton>
	                        <ToolbarButton 
	                            label="Kontrolní hlášení"
	                            onClick={ () => this.setState({ reportType: "kh" }, () => this.refs.paramsForm.submit()) }>
	                            <span className="icon">{ icons.download }</span>
	                        </ToolbarButton>
	                        <ToolbarButton 
	                            label="Přiznání k DPH"
	                            onClick={ () => this.setState({ reportType: "dp" }, () => this.refs.paramsForm.submit()) }>
	                            <span className="icon">{ icons.download }</span>
	                        </ToolbarButton>
	                    </ToolbarButtons>
	                    <ToolbarRow>
	                    </ToolbarRow>
	                </Toolbar>

					<DphParamsForm 
						ref="paramsForm" 
						onSubmit={ this.handleDownload } 
						data={ this.props.defaultParams } 
						periodType={ this.props.settings.periodType } />


					<Attachments 
						unitId={ this.props.unitId } 
						objectType="dph_files" 
						objectId={ 1 }
						/>

				</div>
			);
		} else {
			output = <ActivityIndicator show={ true } type="overlay"/>
		}

		return output;
	}

}

DphReport.contextTypes = {
	router: PropTypes.object.isRequired
};



const mapStateToProps = (state, props) => selector(state);



function mapDispatchToProps(dispatch, props) {
	return {
    	dispatch,
    	fetchSettingsAction: (unit) => dispatch(fetchSettingsAction(unit)),
    	saveSettingsAction: (unit, settings) => dispatch(saveSettingsAction(unit, settings))
  	};
}


export default injectIntl(connect(mapStateToProps, mapDispatchToProps)(DphReport));
