import * as React from "react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import {
	faExternalLinkAlt,
	faInfoCircle,
	faEdit,
} from "@fortawesome/free-solid-svg-icons"
import Scrollbar from "react-scrollbars-custom"
import {
	getTimeDate,
	getPriceMasked,
	getUrlIcon,
	getValuationUSDT,
	getArrayUniqueValues,
	getObjExchangeByExchangeId,
} from "../common"
import { CONSTANTS } from "../constants"
import { IReportAllUserOrders } from "../types"

export const ReportAllUserOrders: React.FC<IReportAllUserOrders> = props => {
	const {
		merchantOrders,
		currentCourses,
		scrollStyle,
		// userId,
		getEditableOrder,
	} = props

	// проверка необходимости футера
	const isFooter =
		getArrayUniqueValues({ nameField: "asset", arrayItems: merchantOrders })
			.length === 1
			? true
			: false
	const isBuySide =
		merchantOrders.length !== 0 && merchantOrders[0].tradeType === "BUY"
			? true
			: false
	const ticker =
		merchantOrders.length !== 0
			? ` ${merchantOrders[0].asset}/${merchantOrders[0].fiat}`
			: ""
	let totalAmount = 0
	let totalVolume = 0

	const listOrders =
		merchantOrders && merchantOrders.length !== 0 ? (
			merchantOrders.map((item: any, index: number) => {
				const volumeUSDT: any = getValuationUSDT(
					currentCourses,
					item.asset,
					item.volume
				)
				const objExchange = getObjExchangeByExchangeId(item.exchangeId)
				const amount = +item.amount
				totalAmount += amount
				totalVolume += +item.volume

				// Подсветка/обработка колонки tradeType
				let tableRowClass
				item.tradeType === "BUY"
					? (tableRowClass = "success")
					: (tableRowClass = "danger")

				return (
					<tbody key={index}>
						<tr>
							<td>{index + 1}</td>
							<td className={`table-${tableRowClass}`}>
								<span className="icon-pay-dots">
									{item.tradeType}
									<img
										src={getUrlIcon("iconCurrencyByName", item.asset)}
										className="ml-1"
										alt="-"
										title={item.asset}
									/>
									{item.asset}
								</span>
							</td>
							<td className={`table-${tableRowClass}`}>
								{`${getUrlIcon("FiatSymbol", item.fiat)}  ${getPriceMasked(
									amount.toFixed(2)
								)}`}
							</td>
							<td className="text-right">
								{item.asset === "SHIB"
									? Number(item.price).toFixed(6)
									: getPriceMasked(Number(item.price).toFixed(2))}
								{` ${item.asset}/${item.fiat}`}
							</td>
							<td>
								{item.counterpartRealName === "" ||
								item.counterpartRealName === null
									? item.counterpartNickName
									: item.counterpartRealName.slice(-20)}
							</td>
							<td>
								<span className="icon-pay-dots">
									<img
										src={getUrlIcon("iconPaymentByID", item.payMethodId)}
										alt="-"
										title={item.payMethodName}
									/>
								</span>
								{`| ${
									item.payMerchantAccount === "" ? "xxx" : item.payMerchantAccount
								} | `}
								<span className={`text-success`}>{item.orderStatusText}</span>
							</td>
							<td>
								<span className="icon-pay-dots">
									<img
										src={getUrlIcon("logoExchange", item.exchange)}
										className="ml-1"
										alt="-"
										title={item.exchange}
									/>
									{`${item.exchange} | `}
									<FontAwesomeIcon
										icon={faEdit}
										style={{ cursor: "pointer" }}
										className="text-success ml-1"
										title="orderEdit"
										onClick={() => {
											const objOrder = {
												userId: item.userId,
												orderId: item.orderId,
												exchange: item.exchange,
											}
											getEditableOrder(objOrder)
										}}
									/>
									<a
										href={
											item.exchange === "BT"
												? `${objExchange.orderDetail}${item.orderId}/${item.asset}/${item.fiat}`
												: `${objExchange.orderDetail}${item.orderId}`
										}
										target="_blank"
										rel="noopener noreferrer"
										className="text-warning ml-1"
										title="orderDetails"
									>
										<FontAwesomeIcon icon={faInfoCircle} />
									</a>
								</span>
							</td>
							<td className="text-right">{getTimeDate(item.dateOrder)}</td>
						</tr>
						<tr>
							<td></td>
							<td>
								{`≈ $`}
								{item.asset === "SHIB"
									? Number(item.priceAssetUSDT).toFixed(8)
									: getPriceMasked(Number(item.priceAssetUSDT).toFixed(2))}
							</td>
							<td>{`≈ $${volumeUSDT}`}</td>
							<td className="text-right">
								{item.asset === "SHIB" ||
								item.asset === "RUB" ||
								item.asset === "USDT" ||
								item.asset === "USDC" ||
								item.asset === "BUSD" ||
								item.asset === "HUSD" ||
								item.asset === "TUSD"
									? `${Number(item.volume).toFixed(2)}  ${item.asset}`
									: `${Number(item.volume).toFixed(8)}  ${item.asset}`}
							</td>
							<td>
								{item.asset === "SHIB"
									? `Fee: ${Number(item.commission).toFixed(2)}  ${item.asset}`
									: `Fee: ${Number(item.commission).toFixed(8)}  ${item.asset}`}
							</td>
							<td>
								N/A{/* {item.taker.userStatsRet.registerDays} */}
								{" | "}
								{Number(merchantOrders).toFixed(0)}
								{" | "}
								N/A{/* {(parseFloat(merchantRatio) * 100).toFixed(1) + " %"} */}
								{" | "}
								<span className="span-link">
									<a
										href={
											item.exchange === "BT"
												? `${objExchange.merchantDetail}${item.counterpartId}/${item.asset}/${item.fiat}`
												: `${objExchange.merchantDetail}${item.counterpartId}`
										}
										target="_blank"
										rel="noopener noreferrer"
										className="text-warning"
										title="merchantDetails"
									>
										<FontAwesomeIcon icon={faExternalLinkAlt} />
									</a>
								</span>
							</td>
							<td>
								{item.counterpartСlientType
									? `****${item.userId.slice(-4)} | ${item.counterpartСlientType}`
									: `****${item.userId.slice(-4)}`}
							</td>
							<td className="text-right">
								{item.exchange === "MG" ||
								item.exchange === "KC" ||
								item.exchange === "BP" ||
								item.exchange === "BT" ||
								item.exchange === "CX" ||
								item.exchange === "BX" ||
								item.exchange === "AX" ||
								item.exchange === "XG"
									? `****${item.orderId.slice(-8)}`
									: item.orderId}
							</td>
						</tr>
					</tbody>
				)
			})
		) : (
			<tbody>
				<tr>
					<td colSpan={9}>{CONSTANTS.ERROR_TEXT}</td>
				</tr>
			</tbody>
		)

	return (
		<div className="container">
			<div className="row">
				<Scrollbar style={scrollStyle}>
					<table className="table table-hover table-striped table-sm">
						<thead>
							<tr>
								<th scope="col">#</th>
								<th scope="col">Side | Crypto</th>
								<th scope="col">Summ</th>
								<th scope="col" className="text-right">
									Price | Quantity
								</th>
								<th scope="col" className="tbl-header">
									<span>PayNumber</span>
									<span>Merchant</span>
								</th>
								<th scope="col" className="tbl-header">
									<span>Status</span>
									<span>Reg | Orders | Rate</span>
								</th>
								<th scope="col" className="tbl-header">
									<span>Details</span>
									<span>UserId | Client</span>
								</th>
								<th scope="col">Id | Date</th>
							</tr>
						</thead>
						{listOrders}
						{isFooter ? (
							<tfoot>
								<tr
									style={{
										backgroundColor: isBuySide ? "lightgreen" : "pink",
										color: "black",
									}}
								>
									<td>#</td>
									<td style={{ fontWeight: "bold" }}>TOTAL:</td>
									<td>{`${getUrlIcon("FiatSymbol", "RUB")}  ${getPriceMasked(
										totalAmount.toFixed(2)
									)}`}</td>
									<td>{(totalAmount / totalVolume).toFixed(2) + ticker}</td>
									<td></td>
									<td></td>
									<td></td>
									<td style={{ fontWeight: "bold" }}></td>
								</tr>
							</tfoot>
						) : null}
					</table>
				</Scrollbar>
			</div>
		</div>
	)
}
