import * as React from "react";
import { RouteComponentProps } from "react-router-dom";
import { ProductController_GetProduct } from "../../../apiClient/routes";
import { IProductItem } from "../../../apiModels/ViewModels";
import ProductDetailFooter from "./products/ProductDetailFooter";
import { NewCarousel } from '../../common/NewCarousel';
import http from "../../../services/httpService";
import parse from "html-react-parser";

type ProductDetailProps = RouteComponentProps<{ id: string }> & {
	onAddToCartClick(productId: number, amount: number): void
};

type ProductDetailState = {
	product: IProductItem,
	amount: number,
	outOfStock: boolean,
	errors: string[]
};

class ProductDetail extends React.Component<ProductDetailProps, ProductDetailState> {
	constructor(props: ProductDetailProps) {
		super(props);

		this.state = {
			product: {
				id: 0,
				name: '',
				price: 0,
				availableQuantity: 0,
				reducedPrice: 0,
				description: '',
				productCategoryID: 0,
				productCategoryName: '',
				productImageIDs: []
			},
			amount: 1,
			outOfStock: false,
			errors: []
		}
	}

	componentDidMount() {
		document.title = "Detail produktu";

		let productId = this.props.match.params.id;

		http.get<IProductItem>(ProductController_GetProduct(productId)).then((products) => {
			const product = products.data;
			this.setState({ product, outOfStock: (product.availableQuantity <= 0) });
		})
		.catch(e => {
			console.log(e);
			// pri chybe (nenalezeni produktu apod.), presmerovani na vypis produktu
			this.props.history.push("/");
		});
	}

	increaseDecreaseAmount = (newAmount: number): void => {
		this.setState({ amount: newAmount });
	}

	handleAmountChange = (e: React.FormEvent<HTMLInputElement>): void => {
		this.setState({ amount: ~~e.currentTarget.value });
	}

	handleAddToCartClick = (): void => {
		const { amount, product } = this.state;
		let errors: string[] = [];

		if (amount <= 0 || amount > product.availableQuantity) {
			errors.push(`Zvolené množství: <strong>${amount}</strong> kusů není na skladě! Aktuálně dostupné množství je: <strong>${this.state.product.availableQuantity}</strong> kusů.`);
			this.setState({ errors });
		} else {
			this.setState({ errors });
			this.props.onAddToCartClick(product.id, amount);
		}
	}

	render() {
		const { amount, outOfStock, product, errors } = this.state;

		return (
			<section className="product-details">
				{product.id !== 0
					? <div className="container">
						<div className="row">
							<div className="col-lg-6 col-md-6">
								<div className="product__details__pic">
									<NewCarousel imageIds={product.productImageIDs} />
								</div>
							</div>
							<div className="col-lg-6 col-md-6">
								<div className="product__details__text">
									<h3>{product.name}</h3>
									<div className="product__details__rating">
										{/*<i className="fa fa-star"></i>*/}
										{/*<i className="fa fa-star"></i>*/}
										{/*<i className="fa fa-star"></i>*/}
										{/*<i className="fa fa-star"></i>*/}
										{/*<i className="fa fa-star-half-o"></i>*/}
										<span>Kategorie: {product.productCategoryName}</span>
									</div>
									{/* Zobrazit preskrtnutou puvodni cenu a napsat, ze akcni cena */}
									<div className="product__details__price">
										{product.reducedPrice !== undefined && product.reducedPrice > 0 && product.reducedPrice < product.price
											? product.reducedPrice.toFixed(2)
											: product.price.toFixed(2)} Kč
									</div>
									{outOfStock
										? ''
										: <div>
											<div className="product__details__quantity">
												<small>Množství:</small>
												<div className="quantity">
													<div className={errors.length ? "pro-qty input__error" : "pro-qty"}>
														<i onClick={() => this.increaseDecreaseAmount(amount - 1)} className="fas fa-minus qtybtn"></i>
														<input type="text" onChange={(e) => this.handleAmountChange(e)} value={amount} pattern="[1-9]*" ></input>
														<i onClick={() => this.increaseDecreaseAmount(amount + 1)} className="fas fa-plus qtybtn"></i>
													</div>
												</div>
											</div>
											<button onClick={this.handleAddToCartClick} className="primary-btn" disabled={outOfStock}>DO KOŠÍKU</button>
											<br />
											{errors.length
												? <span className="error-message">{parse(errors[0])}</span>
												: null}
											<br />
											{outOfStock
												? <span className="error-message">Omlouváme se, ale tento produkt není momentálně skladem!</span>
												: null}
										</div>}
									<ul>
										<li>
											<strong>Množství na skladě: </strong>
											{product.availableQuantity <= 0
												? <span className="text-danger font-weight-bold"> Nedostupné</span>
												: (product.availableQuantity > 0 && product.availableQuantity <= 10)
													? <>{product.availableQuantity}</>
													: <>více než <b>10</b> kusů</>
											}
										</li>
										{/*<li><b>Dodací lhůta:</b> <span>01 day shipping. <samp>Free pickup today</samp></span></li>*/}
										<li><strong>Dodací lhůta:</strong>obvykle do 5 pracovních dnů</li>
										{/*<li><strong>Velikost:</strong> 10 kg</li>*/}
									</ul>
								</div>
							</div>
							{/* Rozmyslet si jak budu zobrazovat popis produktu a pripadne pdf nutricnich hodnot */}
							<div className="col-lg-12">
								<ProductDetailFooter productDescription={product.description} />
							</div>
						</div>
					</div>
				: ''
				}
			</section>
		);
	}
}

export default ProductDetail;