import React from 'react';
import Modularity from 'modularity-front';
import {Divider, Col , Row } from 'react-materialize';
import './mini-cart.css';
import CartIcon from '@material-ui/icons/ShoppingCart';
import Dictionary from '../Services/DictionaryService';

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

class MiniCartModule extends Modularity.Module {
	constructor(props) {
		super(props);
		this.state = {
			products:{
			}
		}
		this.addProduct.onUpdate((value) => {
			if(!value || !value.id){
				return;
			}
			let products = {...this.state.products};
			let key = value.id;
			let val = {
				image:value.image,
				name:value.name,
				price:value.price,
				quantity:value.quantity				
			}
			console.log(val);
			// Thats me punk writing this code below !!!
			key in products ? products[key].quantity+=val.quantity : products[key] = val;
			this.setState({products});
			this._save(products);
			this.products.set(products);
		});
		this._load();
	}

	_minBut = (e,id) => {
		
		let products = this.state.products;
		if(products[id].quantity > 1 ) {
			products[id].quantity -= 1;
		}else{
			delete products[id]
		}
		this.setState({products});
		this._save(products);
		this.products.set(products);
		
	}

	_addBut = (e,id) => {
		
		let products = this.state.products;
		products[id].quantity += 1;
		this.setState({products})
		this.products.set(products);
		this._save(products);
		return false;
	}
	_save = (products) => {
		localStorage.setItem("cart_state",JSON.stringify(products))
	}

	_load = () => {
		let local = localStorage.getItem('cart_state');
		if(local) {
			this.state.products = JSON.parse(local);
			this.products.set(this.state.products);
		}
	}


	cartPage = () => {
		console.log("this")
		this.CoreSystem.go("/orders")
	}

	render() {
		let prods = this.state.products;
		let nameList = Object.keys(prods).map((id,index)=>
	        <li key={id} className="custom-flex basket-row">
	          <div>
	          	<img  className="circle mini_img" src="/yuna.jpg"/>
	          </div>
	          <div className="flex-prod-name">
	          	 <Link link={"/product/" + id}>{prods[id].name}</Link>
	          </div>
	          <div className="cust-flex">
		          <div>
		          	<span onClick = {(e) => { this._minBut(e,id) }} className="quantity_but">&#8722;</span>
		          </div>
		          <div>
		          	{prods[id].quantity}
		          </div>
		          <div>
		          	<span onClick = {(e) => { this._addBut(e,id) }}  className="quantity_but">&#43;</span>
		          </div>
		         
	          </div>
	          <div className="prod_price">
		          	{prods[id].price} €
		      </div>
	        </li>
        );

		let selector = false;
		if(Object.keys(prods).length > 0) {
			selector = true;
		}
		
		let total = Object.keys(prods).reduce((total, key) => total + prods[key].quantity * prods[key].price, 0).toFixed(2);
		
		console.log("############",total)
		return <div  className={"dropdown " + (selector ? "HAHAHA" : "NO")} style={{
				verticalAlign: 'bottom',
			    display: 'flex',
			    height: 64,
			    justifyContent: 'center',
			    flexDirection: 'column'
			}}>
				<CartIcon onClick = {(e) => this.cartPage()} className="cart_size"/>
				{selector ? 
				<div className="dropdown-cont cart" key={Math.random()}>
			        <div className="cart_title">
			            {Dictionary.get("Your Cart")}
			        </div>
			        <div className="cart_products">
			        	<ol>
			        		{nameList}
			        	</ol>
			        </div>
			        <Row className="cart_total">
		                    <span>{Dictionary.get("Total")}</span><b>{total} €</b>
		            </Row>
		            <Row>
		            	<div  className="btn order_but" onClick={ (e) => this.cartPage() }>
		            	{Dictionary.get("Checkout")}
		            	</div>
		            </Row>
	      	 	</div>
				:
			  	<div className="dropdown-cont cart empty" key={Math.random()}>
					<div className="empty-cart">
					  {Dictionary.get("Empty cart")}
					</div>
			  	</div>}
				{super.render()}
		    </div>;
				    
	}
}



MiniCartModule.EditPosition = "center";
MiniCartModule.Inputs = {
	cartImage:{
		type:Module.Types.Text,
		defaultValue:"/mini_cart.png"
	},
	addProduct:{
		type:Module.Types.Object
	}

		
}

MiniCartModule.Outputs ={
	products:{		
	}
}

MiniCartModule.Category = "sxoinas";
export default MiniCartModule;