import * as React from "react";
import { Link, RouteComponentProps } from "react-router-dom";
import { IProductInStockDto, IShoppingCartItem } from "../../../apiModels/ViewModels";
import ShoppingCartList from "./ShoppingCart/ShoppingCartList";
import { ProductController_AreProductsInStock } from "../../../apiClient/routes";
import http from "../../../services/httpService";
import { WarningModal } from "../../common/WarningModal";

type ShoppingCartProps = RouteComponentProps & {
	cartItems: IShoppingCartItem[],
	onAddToCartClick(productId: number, amount: number): void,
	onDeleteFromCartClick(productId: number): void,
	onRemoveFromCartClick(productId: number, amount: number): void
};

class ShoppingCart extends React.Component<ShoppingCartProps> {
	state = {
		modalBodyText: [''],
		modalTitle: 'Upozornění',
		showModal: false
	}

	componentDidMount() {
		document.title = "Košík";
	}

	calculateTotalPrice = (): number => {
		let totalPrice: number = 0;
		this.props.cartItems.forEach(item => {
			totalPrice += (Math.round(((item.price * item.amount) + Number.EPSILON) * 100) / 100)
		})

		return totalPrice;
	}

	productsInStock = async (): Promise<void> => {
		let products = this.props.cartItems.map((cartItem) => {
			return {
				id: cartItem.productID,
				name: cartItem.name,
				count: cartItem.amount,
				errorMessage: ''
			};
		});

		await http.post<IProductInStockDto[]>(ProductController_AreProductsInStock, products).then(async response => {
			if (response.status == 200) {
				// presmerovat na checkout
				// Posilam location.state, abych zachoval jiz vyplnene informace v checkoutu
				this.props.history.push("/checkout", this.props.location?.state);
			}
		}).catch(async e => {
			console.log(e);

			var errorArr: string[] = [];
			await e.response.data.forEach((item: IProductInStockDto) => {
				errorArr.push(item.errorMessage);
			});

			console.log("nove err pole: ", errorArr);
			this.setState({ modalBodyText: errorArr, showModal: true });
		});
	}

	handleHideWarningModal = () => {
		this.setState({ showModal: false });
	}

	render() {
		const { modalTitle, modalBodyText, showModal } = this.state;
		const { cartItems, onAddToCartClick, onDeleteFromCartClick, onRemoveFromCartClick } = this.props;
		return (
			<React.Fragment>
				{cartItems.length > 0
					? <section className="shoping-cart">
						<div className="container">
							<h3 className="mb-4">Nákupní košík</h3>
							<div className="row">
								<div className="col-lg-12">
									<ShoppingCartList
										cartItems={cartItems}
										onAddToCartClick={onAddToCartClick}
										onDeleteFromCartClick={onDeleteFromCartClick}
										onRemoveFromCartClick={onRemoveFromCartClick}
									/>
								</div>
							</div>
							<div className="row">
								<div className="col-lg-12">
									<div className="shoping__cart__btns">
										<Link to="/" className="primary-btn cart-btn">POKRAČOVAT V NAKUPOVÁNÍ</Link>
									</div>
								</div>
								<div className="col-lg-6">
								</div>
								<div className="col-lg-6">
									<div className="shoping__checkout">
										<h5>Cena celkem</h5>
										<ul>
											<li>Mezisoučet <span>{this.calculateTotalPrice().toFixed(2)} Kč</span></li>
											<li>Celkově <span>{Math.round(this.calculateTotalPrice())} Kč</span></li>
										</ul>
										<button className="primary-btn" onClick={this.productsInStock} >VYTVOŘIT OBJEDNÁVKU</button>
									</div>
								</div>
							</div>
						</div>
					</section>
					:
					<div className="container empty__cart">
						<div className="row">
							<div className="col-lg-12">
								<div className="card">
									<div className="card-body cart">
										<div className="col-sm-12 empty-cart-cls text-center">
											<img src="/img/cart/empty_cart.png" width="250" className="img-fluid mb-2" />
											<h3><strong>Váš košík je prázdný</strong></h3>
											<h4>Přidejte nějakou položku :)</h4>
											<Link to="/" className="primary-btn cart-btn m-3">ZPĚT NA PRODUKTY</Link>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				}

				<WarningModal
					bodyText={modalBodyText}
					modalTitle={modalTitle}
					show={showModal}
					onHide={this.handleHideWarningModal}
				/>
			</React.Fragment>
		);
	}
}

export default ShoppingCart;