import * as React from "react";
import axios from "axios";
import { Link, RouteComponentProps } from "react-router-dom";
import { OrderController_GetOrderDetail, ProductImageController_GetImage } from "../../../../apiClient/routes";
import { IOrderDetailVM } from "../../../../apiModels/ViewModels";
import { OrderDetailAddresses } from "./Orders/OrderDetailAddresses";
import { OrderDetailHeader } from "./Orders/OrderDetailHeader";
import http from "../../../../services/httpService";

type OrderDetailProps = RouteComponentProps<{ id: string }>

class OrderDetail extends React.Component<OrderDetailProps> {
	state = {
		order: {} as IOrderDetailVM
	};

	componentDidMount() {
		let orderId = this.props.match.params.id;

		if (orderId) {
			http.get<IOrderDetailVM>(OrderController_GetOrderDetail(orderId)).then((response) => {
				const order = response.data;
				this.setState({ order });
			})
			.catch(e => {
				console.log(e);
				// pri chybe (nenalezeni objednavky apod.), presmerovani na vypis produktu
				this.props.history.push("/");
			});
		}
	}
	
	render() {
		const { order } = this.state;

		if (order.orderItems !== undefined) {
			return (
				<React.Fragment>
					<section className="order-detail">
						<div className="container">

							<OrderDetailHeader order={order} />

							{/* Order items list */}
							<div className="row">
								<div className="col-lg-12">
									<div className="order__detail__table">
										<table>
											<thead>
												<tr>
													<th className="order__detail__item__name">Produkt</th>
													<th>Cena</th>
													<th>Kusů</th>
													<th className="order__detail__total__price">Cena celkem</th>
												</tr>
											</thead>
											<tbody>
												{order.orderItems.map(orderItem => {
													return <tr key={`orderDetailItem-${orderItem.id}`}>
														<td className="order__detail__item">
															<img src={(orderItem.imageID !== undefined && orderItem.imageID !== null && orderItem.imageID !== 0)
																? `${axios.defaults.baseURL + ProductImageController_GetImage(orderItem.imageID.toString())}`
																: "img/cart/cart-1.jpg"} width="100px" />
															<Link to={`/product/${orderItem.productID}`}><h5>{orderItem.name}</h5></Link>
														</td>
														<td className="order__detail__price">{orderItem.price} Kč</td>
														<td>{orderItem.amount}</td>
														<td>{orderItem.totalPrice} Kč</td>
													</tr>
												})}
											</tbody>
										</table>
									</div>
								</div>
							</div>

							<OrderDetailAddresses order={order} />

						</div>
					</section>
				</React.Fragment>
			);
		} else {
			return null;
		}
	}
}

export default OrderDetail;