import React from 'react';
import Modularity from 'modularity-front';
import { Row, Col, Card } from 'react-materialize';
import './UserAccount.css'


import Form from '../../Modules/Form';
import AddressBox from '../../Modules/AddressBox';
import ArraySelector from '../../Modules/ArraySelector';
import AddressInputs from '../../Inputs/AddressInput';
import TableData from '../../HigherModules/TableData';
import ClientInputs from '../../Inputs/ClientInput';
import Merge from '../../helpers/Merge';
import Toast from '../../helpers/Toast';

import Addresses from '../../HigherModules/AddressesDisplay';

import Repository from '../../Services/Repository';
import UserService from '../../Services/UserService';

import Dictionary from '../../Services/DictionaryService';

import { Button } from 'react-materialize';

const Module = Modularity.Module;
// let Link = Modularity.Modules.Link;

class UserAccount extends Modularity.Module {
	constructor(props){
		super(props);
		this.state = {
			view: "info"
		}
		//this.getProfile();
		this.addressRepo = new Repository('addresses', this.Token.value);
		this.accountRepo = new Repository('accounts', this.Token.value);
		this.ordersRepo = new Repository('orders', this.Token.value, [{type: "descending", field: "createdAt"}]);
		this.userService = new UserService({});
		this.Token.onUpdate(() => this.handleToken())
		this.handleToken();
		this.RoutingSystem.onRouteChange("UserAccount", () => {
			this.checkRoute();
		})
		setTimeout(() => this.checkRoute(), 0);
	}

	checkRoute() {
		let route = this.RoutingSystem.getRoute().url || '';
		if(route.endsWith("/orders")) {
			this.setState({view: "orders"});
		} else if( route.endsWith("/addresses") ) {
			this.setState({view: "addresses"});
		} else {
			this.setState({view: "info"});
		}
	}

	updateUser() {
		this.userService.getUser(this.Token.value)
		.then((user) => this.setState({user}));
	}

	handleToken() {
		if(this.Token.value === undefined) return;
		if(this.Token.value === "missing" && this.RoutingSystem.getRoute().url !== "/login" && this.routeMatch()) {
			this.CoreSystem.go('/login', { ref: this.RoutingSystem.getRoute().url }, true)
		}
		this.accountRepo.setToken(this.Token.value);
		this.addressRepo.setToken(this.Token.value);
		this.ordersRepo.setToken(this.Token.value);

		this.updateUser();
		this.forceUpdate();
	}

	routeMatch() {
		return this.RoutingSystem.getRoute().url.startsWith(this.baseURL.value);
	}

	updateUserInfo(data) {
		this.accountRepo.update(this.state.user.Account.id, data).then(() => this.updateUser()).then(() => Toast.notify(Dictionary.get("Successfully updated user info")));
	}

	changePass(data) {
		if(data.npass !== data.rpass) {
			Toast.error("New Passwords are different");
			return;
		}
		this.userService.changePass(this.Token.value, data.cpass, data.npass)
		.then(() => Toast.notify("Password changed"))
		.catch(() => Toast.error("Wrong credentials"));
	}
	_viewOrder(order) {
		console.log("sss",order.id)
		this.CoreSystem.go('/profile/order/'+order.id)
	}

	render(){
		const Link = (props) => <div onClick={() => {
			this.CoreSystem.go(props.link)
		}}>{props.children}</div>;
		return( this.state.user ?  
		<div className={"row UserAccount " + this.ClassName.value} >
			<div className={'col s12 m4 l3 Menu '}>
				<div className="Menu_container">
					<h6 className="Menu_header">{Dictionary.get("User Profile")}</h6>
					
					<Link link={'/user/orders'} className={this.state.view === "orders" && 'selected'}>
						<i className="fa fa-shopping-basket"></i>
						<span>{Dictionary.get("Orders")}</span>
					</Link>
					<Link link={'/user'} className={this.state.view === "info" && 'selected'}>
						<i className="fa fa-user"></i>
						<span>{Dictionary.get("Account information")}</span>
					</Link>
					<Link link={'/user/addresses'} className={this.state.view === "addresses" && 'selected'}>
						<i className="fa fa-home"></i>
						<span>{Dictionary.get("Addresses")}</span>
					</Link>
				</div>
			</div>
			<div className={'col s12 m8 l9 wrapper'}>
			<Card className="">
				{this.state.view === "orders" && <Orders service={this.ordersRepo} viewOrder = {(e) => this._viewOrder(e) } ></Orders>}
				{this.state.view === "info" && <Info account={this.state.user.Account} onSubmit={(data) => this.updateUserInfo(data)} onChangePassSubmit={(data) => this.changePass(data)}></Info>}
				{this.state.view === "addresses"  && <div>{Dictionary.get("My addresses")}<br /><Addresses key={this.addressRepo.token} service={this.addressRepo}></Addresses></div>}
			</Card>
			</div>
			{super.render()}
		</div> : null
		)
			
	}
	
}


class Orders extends React.Component {
	constructor(props) {
		super(props);
		this.state = {}
		this.tableHeaders = {
	        "Αριθμός παραγγελίας" : "id",
	        "Ημερομηνία παραγγελίας": {
	        	field: "createdAt",
	        	type: "date"
	        },
	        "Κατάσταση": "status",
	        "Ποσό" : {
	        	field: "amount",
	        	suffix: " €",
	        	precision: 2
	        }
	    };
	}


	render() {
		return  <div>
					<TableData service={this.props.service} TableHeaders={this.tableHeaders} onView = {(e) => this.props.viewOrder(e)}/>
				</div>;
	}
}

class Info extends React.Component {
	constructor(props) {
		super(props);
		this.state = {}
		this.passwordInputs = {
			"cpass":{
				type:"text",
				placeholder:"Current password",
				columns:"col s12",
				filter: {
					password: true,
					required: true
				}
			},
			"npass":{
				type:"text",
				placeholder:"New password",
				columns:"col s12",
				filter: {
					password: true,
					required: true
				}
			},
			"rpass":{
				type:"text",
				placeholder:"Repeat new password",
				columns:"col s12",
				filter: {
					password: true,
					required: true
				}
			},
		}
	}


	render() {
		return  <div className="Info">
					<h6 className="Title_Container">
						<div className="title">Οι πληροφοριες μου</div>
					</h6>
					<div className="Content">
			      		<Form FormInputs = {Merge(ClientInputs, this.props.account || {})} activeButton = {true} button = {'Αποθήκευση'}
			      		onSubmit={(d) => this.props.onSubmit(d)}/>
					</div>
					<h6 className="Title_Container">
						<div className="title">Αλλαγή κωδικού</div>
					</h6>
					<div className="Content">
			      		<Form FormInputs = {this.passwordInputs} activeButton = {true} button = {'Αλλαγή κωδικού'}
			      		onSubmit={(d) => this.props.onChangePassSubmit(d)}/>
					</div>
				</div>;
	}
}

UserAccount.Inputs = {
	Account:{
		type:Module.Types.Object
	},
	Token: {
		type: Module.Types.Text
	},
	ClassName: {
		type: Module.Types.Text
	},
	baseURL: {
		type: Module.Types.Text,
		defaultValue: "/user"
	}
}
UserAccount.Category = "Sxoinas Packages";

export default UserAccount;