import * as React from "react"
import $ from "jquery"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import {
	faDownload,
	faBalanceScale,
	faDollarSign,
} from "@fortawesome/free-solid-svg-icons"
import { faBtc } from "@fortawesome/free-brands-svg-icons"
import { STYLES, CONSTANTS } from "../constants"
import { IReportTotalSumm } from "../types"
import {
	startModalAlert,
	getUrlIcon,
	getValuationUSDT,
	getUserPropertyByExchange,
} from "../common"
import Scrollbar from "react-scrollbars-custom"

export const ReportTotalSumm: React.FC<IReportTotalSumm> = props => {
	const {
		userProfile,
		scrollStyle,
		dataConstants,
		currentCourses,
		getGroupItems,
		handlerPopupWindow,
		handlerFilterDetails,
	} = props

	const { exchanges, currencies } = dataConstants

	const arrParams = exchanges.filter((item: any) => {
		item.summ = 0
		item.prefix = item.shortName
		return item.status ? item : null
	})

	const arrAssets = currencies.filter((item: any) => {
		return item.currencyType === "coin" ? item : null
	})

	const [valuationUSDT, handlerValuation] = React.useState(true)

	const thItems = arrParams.map((item: any, index: number) => {
		return (
			<th scope="col" key={index}>
				{item.shortName}
			</th>
		)
	})

	// Получение баланса по asset и по конкретному аккаунту SPOT, P2P, FUT
	const getBalanceAccount = (
		assetName: string,
		arrBalance: any,
		nameAccount: string,
		param1: string,
		param2: string
	) => {
		let summFree = 0
		let summFreeze = 0
		let summTotal = 0
		if (arrBalance.length !== 0) {
			for (let i = 0; i < arrBalance.length; i++) {
				const asset = arrBalance[i].currency
				if (assetName === asset) {
					summFree = +arrBalance[i][param1]
					summFreeze = +arrBalance[i][param2]
					summTotal =
						nameAccount === "EARN" ? summFreeze : summFree + summFreeze
				}
			}
		}
		return summTotal
	}

	// Получение суммарного баланса по бирже
	const getTotalSummByExchange = (
		arr: any,
		shortName: string,
		newSumm: number
	) => {
		for (let i = 0; i < arr.length; i++) {
			if (arr[i].shortName === shortName) {
				arr[i].summ += newSumm
			}
		}
	}

	// Получение баланса по asset и по конкретной бирже BN, HB, KX....
	const getSummBalanceByAsset = (assetName: string, shortName: any) => {
		let result: any = 0
		let totalSPOT: any = 0
		let totalP2P: any = 0
		let totalFUT: any = 0
		let totalEARN: any = 0
		for (let k = 0; k < arrParams.length; k++) {
			if (arrParams[k].shortName === shortName) {
				const balances = getUserPropertyByExchange(
					"currentBalances",
					arrParams[k].id,
					userProfile.userProperties
				)
				totalSPOT = getBalanceAccount(
					assetName,
					balances.spotBalance,
					"SPOT",
					"available",
					"frozen"
				)
				totalP2P = getBalanceAccount(
					assetName,
					balances.p2pBalance,
					"P2P",
					"available",
					"frozen"
				)
				totalFUT = getBalanceAccount(
					assetName,
					balances.futBalance,
					"FUT",
					"available",
					"frozen"
				)
				totalEARN = getBalanceAccount(
					assetName,
					balances.earnBalance,
					"EARN",
					"available",
					"frozen"
				)
				result = (totalSPOT + totalP2P + totalFUT + totalEARN).toFixed(5)
				getTotalSummByExchange(
					arrParams,
					arrParams[k].shortName,
					+getValuationUSDT(currentCourses, assetName, result)
				)
			}
		}
		return result
	}

	const lowBalanceLimit = 0.91
	const currentAssets: any[] = []
	const listItem: any =
		Array.isArray(currentCourses) && currentCourses.length === 0 ? (
			<tr>
				<td colSpan={arrParams.length + 2}>{CONSTANTS.ERROR_TEXT}</td>
			</tr>
		) : (
			arrAssets.map((item: any, index: number) => {
				// суммарный баланс по конкретной монете
				let summAssetTotal = 0
				const tdItems = arrParams.map((param: any, idx: number) => {
					const summAsset = +getSummBalanceByAsset(
						item.currency,
						param.shortName
					)
					summAssetTotal += summAsset
					const summAssetUSDT = +getValuationUSDT(
						currentCourses,
						item.currency,
						summAsset
					)
					if (summAssetUSDT > lowBalanceLimit)
						currentAssets.push({
							summ: summAssetUSDT,
							asset: item.currency,
							exchange: param.shortName,
							exchangeId: param.id,
							volume: summAsset,
						})
					const x = +getValuationUSDT(currentCourses, item.currency, summAsset)
					const visualAsset = x > 0 ? x : "--"
					return (
						<td key={idx}>
							{valuationUSDT ? visualAsset : summAsset.toFixed(5)}
						</td>
					)
				})

				// пропускаем нулевой баланс монеты
				const s = +getValuationUSDT(
					currentCourses,
					item.currency,
					summAssetTotal
				)
				if (s < lowBalanceLimit) return null

				return (
					<tr key={index}>
						<td style={{ width: "20%" }}>
							<span className="icon-pay-dots p-1">
								<img
									src={getUrlIcon("iconCurrencyByName", item.currency)}
									className="ml-1"
									alt="-"
									title={item.currency}
								/>
								{item.currency === "DOGETHER" ? "DOGR" : item.currency}
							</span>
						</td>
						{tdItems}
						<td
							style={{
								backgroundColor: "lightskyblue",
								color: "black",
								fontWeight: "bold",
							}}
						>
							{valuationUSDT
								? // `${symbol} ` +
								  getValuationUSDT(currentCourses, item.currency, summAssetTotal)
								: summAssetTotal.toFixed(5)}
						</td>
					</tr>
				)
			})
		)

	// const symbol = getUrlIcon("FiatSymbol", "USD")
	const symbol = ""
	const objBalancesDB = {
		balances: currentAssets,
	}

	const td_tfootItems = arrParams.map((item: any, idx: any) => {
		return (
			<td key={idx}>
				{valuationUSDT ? `${symbol} ${item.summ.toFixed(2)}` : `--`}
			</td>
		)
	})

	// суммарно по всем биржам
	const totalSumm = arrParams.reduce((a: any, b: any) => {
		return a + b.summ
	}, 0)

	return (
		<div className="container">
			<div className="row">
				<Scrollbar style={scrollStyle}>
					<table className="table table-hover table-striped table-sm">
						<thead>
							<tr className="bg-dark text-white">
								<th scope="col" className="text-left">
									<i
										className="btn-sm btn-outline-warning"
										title="GetBalance"
										// disabled
										onClick={() => {
											if (arrParams.length !== 0) {
												const objParams = {
													userId: userProfile.id,
													typeItems: "allBalances",
												}
												getGroupItems(objParams)
											} else {
												handlerPopupWindow(
													STYLES.WARNING,
													"arrParams: " + CONSTANTS.COOKIE_EMPTY
												)
												startModalAlert()
											}
										}}
									>
										<FontAwesomeIcon icon={faBalanceScale} />
									</i>
									<i
										className="btn-sm btn-outline-danger"
										title="InsertBalance"
										// type="button"
										// disabled
										onClick={() => {
											$("#modal-insertBalance").modal("show")
											handlerFilterDetails("", "balanceDetails", objBalancesDB)
										}}
									>
										<FontAwesomeIcon icon={faDownload} />
									</i>
									{valuationUSDT ? (
										<i
											className="btn-sm btn-outline-info"
											onClick={() => handlerValuation(!valuationUSDT)}
											title="TotalAsset"
										>
											<FontAwesomeIcon icon={faBtc} />
										</i>
									) : (
										<i
											className="btn-sm btn-outline-success"
											onClick={() => handlerValuation(!valuationUSDT)}
											title="TotalUSDT"
										>
											<FontAwesomeIcon icon={faDollarSign} />
										</i>
									)}
								</th>
								{thItems}
								<th scope="col">Total, $</th>
							</tr>
						</thead>
						<tbody>{listItem}</tbody>
						<tfoot>
							<tr style={{ backgroundColor: "lightgreen", color: "black" }}>
								<td style={{ fontWeight: "bold" }}>TOTAL, $:</td>
								{td_tfootItems}
								<td style={{ fontWeight: "bold" }}>
									{valuationUSDT
										? // `${symbol} ` +
										  totalSumm.toFixed(2)
										: `000`}
								</td>
							</tr>
						</tfoot>
					</table>
				</Scrollbar>
			</div>
		</div>
	)
}
