import * as React from "react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import {
	faExternalLinkAlt,
	faCheckCircle,
	faEdit,
	faStar as solidStar,
	faInfoCircle,
} from "@fortawesome/free-solid-svg-icons"
import { faStar as regularStar } from "@fortawesome/free-regular-svg-icons"
import { STYLES, CONSTANTS } from "../constants"
import { IListP2POrders } from "../types"
import {
	getPriceMasked,
	getUrlIcon,
	startModalAlert,
	getCostUSDT,
	getPercent,
	getColorPurcent,
	handlerPriceTickers,
	getTickerName,
	replace000ToK,
} from "../common"

// https://github.com/xobotyi/react-scrollbars-custom/tree/master
import Scrollbar from "react-scrollbars-custom"

import "../styles/OrderList.css"

export const ListP2POrders: React.FC<IListP2POrders> = props => {
	const {
		objExchange,
		userProps,
		scrollStyle,
		currentCourses,
		updateUser,
		getEditableAdv,
		handlerPopupWindow,
		handlerUserProfile,
	} = props

	const { id, name, shortName, merchantDetail, advDetail } = objExchange
	const {
		userId,
		userAuth,
		p2pOrders,
		favorites,
		exchangeUserId,
		sellingPriceUSDT,
	} = userProps

	let listOrders: any = (
		<tr>
			<td colSpan={10}>{CONSTANTS.ERROR_TEXT}</td>
		</tr>
	)

	const costHeader: any = (
		<th scope="col" title="USDT Cost">
			Cost, USDT
		</th>
	)
	let totalOrders = 0
	let totalLimit = 0

	if (p2pOrders && p2pOrders.length !== 0) {
		listOrders = p2pOrders.map((item: any, index: number) => {
			// Поверка и Подсветка избранных юзеров
			let favoriteUser = (
				<FontAwesomeIcon
					style={{ cursor: "pointer" }}
					className="mr-1 text-warning"
					icon={regularStar}
					onClick={() => {
						const favoriteItem = {
							nickName: item.conterpartInfo.nickName,
							userId: item.conterpartInfo.uid,
						}
						handlerUserProfile(name, "addItemFavorites", favoriteItem)
						const objUser = {
							exchange: name,
							fieldChangeable: "addFavorite",
							id: userId,
							favoriteUser: {
								nickName: item.conterpartInfo.nickName,
								userId: item.conterpartInfo.uid,
							},
						}
						updateUser(objUser)
					}}
				/>
			)
			let nickNameClass = null
			if (favorites.length !== 0) {
				for (let i = 0; i < favorites.length; i++) {
					if (item.conterpartInfo.uid === favorites[i].userId) {
						favoriteUser = (
							<FontAwesomeIcon
								style={{ cursor: "pointer" }}
								className="mr-1 text-success"
								icon={solidStar}
								onClick={() => {
									handlerUserProfile(
										name,
										"removeItemFavorites",
										item.conterpartInfo.uid
									)
									const objUser = {
										exchange: name,
										fieldChangeable: "removeFavorite",
										id: userId,
										favoriteUser: {
											nickName: item.conterpartInfo.nickName,
											userId: item.conterpartInfo.uid,
										},
									}
									updateUser(objUser)
								}}
							/>
						)
						// подсветка favorite or user
						item.conterpartInfo.uid === exchangeUserId
							? (nickNameClass = "bg-user")
							: (nickNameClass = "bg-favorite")
						break
					}
				}
			}
			const priceAssetFiat = handlerPriceTickers(
				getTickerName("tickerAssetFiat", item.asset, item.fiat),
				currentCourses
			)
			const priceCurrencyUSDT = handlerPriceTickers(
				getTickerName("tickerCurrencyUSDT", item.asset, "USDT"),
				currentCourses
			)

			// переоценка актива в USDT
			const priceCostValue = getCostUSDT(item.price, priceCurrencyUSDT)

			// процент плановой маржи, исходя из объявления SELL USDT/RUB
			const marginPercentage =
				item.tradeType === "BUY" &&
				item.fiat === "RUB" &&
				sellingPriceUSDT !== 0
					? `| ${((+sellingPriceUSDT * 100) / +priceCostValue - 100).toFixed(
							2
					  )} %`
					: ""

			// столбец стоимости актива в USDT
			const costValue = (
				<td className={`${nickNameClass}`}>
					{`$ ${priceCostValue} ${marginPercentage}`}
				</td>
			)
			let surplusAmount = 0
			let classBGtradeType = "success"
			let tradeTypeLocal = "BUY"

			// Подсветка/обработка колонки tradeType
			if (item.tradeType === "BUY") {
				classBGtradeType = "danger"
				tradeTypeLocal = "SELL"
			}

			if (item.asset === "USDT") surplusAmount = +item.amount
			else if (item.asset === "RUB")
				surplusAmount = +item.amount / +priceCurrencyUSDT
			else surplusAmount = +item.amount * +priceCurrencyUSDT

			totalOrders += +item.conterpartInfo.monthOrderCount
			totalLimit += +surplusAmount

			const purcentDeviat = (+item.conterpartInfo.finishRate * 100).toFixed(1)

			const paymentDots = item.payMethods.map((elem: any, index: number) => {
				return (
					<span className="icon-pay-dots" key={index}>
						<img
							alt="-"
							src={getUrlIcon("iconPaymentByID", elem.payId)}
							title={elem.payName}
						/>
					</span>
				)
			})

			let classIsOnline = "text-warning mr-1"
			if (item.conterpartInfo.isOnline === false)
				classIsOnline = "text-danger mr-1"
			else if (item.conterpartInfo.isOnline === true)
				classIsOnline = "text-success mr-1"

			let userURL = ""
			if (
				shortName === "BN" ||
				shortName === "PX" ||
				shortName === "HB" ||
				shortName === "BZ" ||
				shortName === "GX" ||
				shortName === "MG" ||
				shortName === "KC" ||
				shortName === "GT"
			)
				userURL = item.conterpartInfo.uid
			else if (shortName === "KX")
				userURL = `?publicUserId=${item.conterpartInfo.uidPublic}`
			else if (shortName === "BT")
				userURL = item.conterpartInfo.uid + `/${item.asset}/${item.fiat}/item`

			return (
				<tr key={index}>
					<th scope="row">{index + 1}</th>
					<td className={`${nickNameClass} text-left`}>
						{userAuth ? favoriteUser : null}
						<a
							href={merchantDetail + userURL}
							target="_blank"
							rel="noopener noreferrer"
							className={classIsOnline}
							title={`${item.conterpartInfo.nickName} Detals`}
						>
							<FontAwesomeIcon icon={faExternalLinkAlt} />
						</a>
						{`  ${
							shortName === "KX"
								? item.conterpartInfo.nickName.slice(0, 5)
								: item.conterpartInfo.nickName.slice(0, 12)
						}  `}
						{item.conterpartInfo.uid === exchangeUserId &&
						userAuth &&
						shortName === "BN" ? (
							<>
								<FontAwesomeIcon
									icon={faEdit}
									style={{ cursor: "pointer" }}
									className="text-success ml-2"
									title="Edit adv"
									onClick={() => {
										if (
											item.advDetail.tradeType !== item.tradeType &&
											item.advDetail.asset === item.asset &&
											item.advDetail.fiatUnit === item.fiat
										) {
											getEditableAdv({
												userId,
												exchangeId: id,
												exchangeName: name,
												shortName,
												advIdNumber: item.advDetail.advNo,
											})
										} else {
											handlerPopupWindow(STYLES.WARNING, CONSTANTS.ERROR_ADV_P2P)
											startModalAlert()
										}
									}}
								/>
								<a
									href={advDetail + item.advId}
									target="_blank"
									rel="noopener noreferrer"
									className="text-warning ml-2"
									title="advDetail"
								>
									<FontAwesomeIcon icon={faInfoCircle} />
								</a>
							</>
						) : null}
						{item.conterpartInfo.isMerchant !== null &&
						item.conterpartInfo.isMerchant === true ? (
							<FontAwesomeIcon
								className="text-warning"
								title="merchantStatus: true"
								icon={faCheckCircle}
							/>
						) : null}
					</td>
					<td className={`${nickNameClass}`}>
						{item.conterpartInfo.registerDays === ""
							? "--"
							: item.conterpartInfo.registerDays}
						{" | "}
						{item.conterpartInfo.monthOrderCount}
						{" | "}
						<span className={`${getColorPurcent(Number(purcentDeviat))}`}>
							{purcentDeviat}%
						</span>
					</td>
					{costValue}
					<td className={`${nickNameClass}`}>
						{`${getUrlIcon("FiatSymbol", item.fiat)} 
						${
							item.asset === "SHIB"
								? Number(item.price).toFixed(6)
								: getPriceMasked(item.price)
						}`}
					</td>
					<td className={`${nickNameClass}`}>
						{`${getPercent(
							shortName,
							item.price,
							item.tradeType,
							priceAssetFiat,
							priceCurrencyUSDT
						)} %`}
					</td>
					<td className={`${nickNameClass}`}>
						{getUrlIcon("FiatSymbol", item.fiat) + " "}
						{replace000ToK(+item.minLimit)}
						{" - " + replace000ToK(+item.maxLimit)}
					</td>
					<td className={`${nickNameClass}`}>
						{"$ " + replace000ToK(+surplusAmount)}
					</td>
					<td>{paymentDots}</td>
					<td className={`table-${classBGtradeType}`}>
						{tradeTypeLocal}
						<span className="icon-pay-dots ml-2">
							<img
								src={getUrlIcon("iconCurrencyByName", item.asset)}
								alt="*"
								title={item.asset}
							/>
							{item.asset}
						</span>
					</td>
				</tr>
			)
		})
	}

	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" className="text-left">
									Name
								</th>
								<th
									scope="col"
									data-toggle="tooltip"
									data-placement="top"
									title="Зарегистрирован | Всего Ордеров | % Выполнения"
								>
									Reg | Orders | Rate
								</th>
								{costHeader}
								<th scope="col">Price, fiat</th>
								<th scope="col">Dev, %</th>
								<th scope="col">V, Min - Max</th>
								<th scope="col">Limit, USDT</th>
								<th scope="col">PayType</th>
								<th scope="col">Side | Crypto</th>
							</tr>
						</thead>
						<tbody>{listOrders}</tbody>
						<tfoot>
							<tr>
								<td colSpan={2}>Total:</td>
								<td>{`-- | ${totalOrders} | --`}</td>
								<td colSpan={4}></td>
								<td>
									{totalLimit === 0 ? null : `$ ${getPriceMasked(totalLimit)}`}
								</td>
								<td colSpan={2}></td>
							</tr>
						</tfoot>
					</table>
				</Scrollbar>
			</div>
		</div>
	)
}
