import React, { Component } from 'react';

import { injectIntl } from 'react-intl';
import { updateIntl } from 'lib/i18n';
import { appLocales } from '../../config.js';

import { 
	Alert, 
	ActivityIndicator, 
	ButtonBar, 
	Button, 
	DetailTitle,

	ToolbarButton, 
	Toolbar, 
	ToolbarSection, 
	ToolbarButtons, 
	ToolbarRow
} from 'lib/components';

import ProfileSettings from "./ProfileSettings";
import LocaleSettings from "components/LocaleSettingsForm";
import CompanySettings from "components/CompanySettingsForm";
import TaxSettings from "./TaxSettings";
import PersonalSettings from "./PersonalSettings";
import PaymentMethodSettings from './PaymentMethodSettings';
import InvoiceSettings from './InvoiceSettings';

import request from "lib/backend";

import icons from 'constants/icons';
import messages from './messages';
import commonMessages from '../../messages.js';

import { connect } from 'react-redux';
import { 
	selector, 
	fetchProfilesAction,

	previousStep,
	submitProfiles,
	submitLocalSettings,
	submitTaxes,
	submitCompany,
	submitPaymentMethod,
	submitPersonal,
	submitInvoice,
	updateSettings,

	saveAction

} from './redux';
import { fromJS } from 'immutable';


/*
 profile -> local -> tax -> company (+ accounts) -> personal (inv + email)
 */


let pages = [
	{
		title: messages.profileTitle,
		description: messages.profileDescription,
		clazz: ProfileSettings,
		className: "profile",
		icon: "",
		action: submitProfiles,
	},
	{
		title: messages.localeSettingsTitle,
		description: messages.localeSettingsDescription,
		clazz: LocaleSettings,
		className: "locale",
		icon: icons.localSettings,
		action: submitLocalSettings,
	},
	{
		title: messages.taxRatesTitle,
		description: messages.taxRatesDescription,
		className: "tax",
		clazz: TaxSettings,
		icon: icons.taxSettings,
		action: submitTaxes,
	},
	{
		title: messages.companyTitle,
		description: messages.companyDescription,
		className: "company",
		clazz: CompanySettings,
		icon: icons.companySettings,
		action: submitCompany,
	},
	{
		title: messages.paymentMethodsTitle,
		description: messages.paymentMethodsDescription,
		className: "company",
		clazz: PaymentMethodSettings,
		icon: "",
		action: submitPaymentMethod,
	},
	{
		title: messages.invoiceTitle,
		description: messages.invoiceDescription,
		className: "customization",
		clazz: InvoiceSettings,
		icon: icons.invoice,
		action: submitInvoice,
	},
	{
		title: messages.customizationTitle,
		description: messages.customizationDescription,
		className: "customization",
		clazz: PersonalSettings,
		icon: icons.customizationSettings,
		action: submitPersonal,
	},
];

const pagesCount = pages.length - 1;


require("./InitSettings.scss");

class InitSettings extends Component {


	constructor(props) {
		super(props);

		this.save = this.save.bind(this);
		this.changeLocale = this.changeLocale.bind(this);
	}


	componentWillMount() {
		let { data, fetchProfiles, profiles } = this.props;
		if (!profiles) {
			this.props.fetchProfiles();
		}
	}


	async save(data) {
		try {
			data = fromJS(data).toJS();
			if (Array.isArray(data.taxTemplates)) {
				for (let i = 0; i < data.taxTemplates.length; i++) {
					delete data.taxTemplates[i].id;
				}
			}

			data.initialized = true;
			await this.props.saveAction(data);
			window.location.href = "/";
		} catch (e) {
			console.error(e);
		}
	}

	changeLocale(locale, data) {
		let loc = "en";
		for (let i = 0; i < appLocales.length; i++) {
			if (appLocales[i] == locale) {
				loc = locale;
				break;
			}
		}

		this.props.updateSettings({ ...data.toJS(), locale: loc, language: loc })
		this.props.updateIntl(loc);
	}


	render() {
		let { intl, step, pending, stepActions, previousStep, data, profiles, countries, states } = this.props;

		let pageConfig = pages[step];

		let 
			page = null, 
			title = null, 
			description = null, 
			icon = null,
			className = null;

		if (pageConfig) {
			page = <pageConfig.clazz 
						data={ data } 
						onSubmit={ step < pagesCount ? stepActions[step] : this.save } 
						updateIntl={ this.changeLocale } 
						ref="form" 
						disabled={ pending } 
						intl={ intl }
						profiles={ profiles }
						countries={ countries }
						states={ states }
						/>,
			title = pageConfig.title,
			description = pageConfig.description,
			icon = pageConfig.icon;
			className = pageConfig.className;
		}

		return (
			<div className="init-settings-layout">
				<div className="container">
					<div className="relative">
						<div className="logout-div">
							<a href="/auth/logout">
								{ intl.formatMessage({ id: "layout.logoutAction" }) } <i className="icon">{ icons.logout }</i>
							</a>
						</div>
		                <Toolbar>
		                    <ToolbarSection>
		                    	<div className={ className }>
			                        <DetailTitle
			                        	className={ className } 
			                            title={ title && title.id ? intl.formatMessage(title) : null }
			                            titleIcon={ icon }
			                            />
			                    </div>
		                    </ToolbarSection>
		                    <ToolbarButtons>
		                    	{ step > 0 ? (
			                        <ToolbarButton 
			                            label={ intl.formatMessage(commonMessages.buttonPrevious) } 
			                            onClick={ previousStep }>
			                            <span className="icon">{ icons.back }</span>
			                        </ToolbarButton>
			                    ) : null }
		                        <ToolbarButton 
		                            label={ intl.formatMessage(step < pagesCount ? commonMessages.buttonNext : commonMessages.buttonFinish) } 
		                            onClick={ () => this.refs.form.submit() }>
		                            <span className="icon">{ step < pagesCount ? icons.next : icons.ok }</span>
		                        </ToolbarButton>
		                    </ToolbarButtons>
		                    <ToolbarRow>
								<div className="init-settings-jumbotron">
									{ description && description.id ? <p>{ intl.formatMessage(description) }</p> : null }
								</div>
		                    </ToolbarRow>
		                    <ActivityIndicator show={ pending } size="big"/>
						</Toolbar>


						<div className="init-settings-page form-full">
							{ page }
						</div>
						<Alert.Component />
						<ActivityIndicator show={ pending } size="big"/>
					</div>
				</div>

      			<header className="side-top-menu-bar top-menu-bar">
					<div className="menu-logout right">
						<a href="/logout">
							<span className="icon"></span>
						</a>
					</div>
					<div className="clearfix"/>
	  			</header>
			</div>
		);
	}

}



function mapDispatchToProps(dispatch, props) {
	let steps = [];
	for (let i = 0; i < pages.length; i++) {
		if (typeof pages[i].action === "function") {
			steps.push((data) => dispatch(pages[i].action(data)));
		}
	}

	return {
		dispatch,
 		updateIntl: (locale, messages) => dispatch(updateIntl(locale)),
 		fetchProfiles: () => dispatch(fetchProfilesAction()),
 		previousStep: () => dispatch(previousStep()),
 		updateSettings: (data) => dispatch(updateSettings(data)),
 		stepActions: steps,
 		saveAction: (data) => dispatch(saveAction(data))
	};
}

export default injectIntl(connect(selector, mapDispatchToProps)(InitSettings));