import * as React from "react"
import { useState } from "react"
import Scrollbar from "react-scrollbars-custom"
import { CONSTANTS, STYLES } from "../constants"
import { startModalAlert, getUrlIcon, getValuationUSDT } from "../common"
import { IUserBalances } from "../types"

export const UserBalances: React.FC<IUserBalances> = props => {
	const {
		userId,
		objExchange,
		balances,
		currentCourses,
		scrollStyle,
		getBalances,
		handlerPopupWindow,
		transferAsset,
	} = props

	const [valuationUSDT, changeValuation] = useState(false)

	let totalSPOT_USDT = 0
	let totalP2P_USDT = 0
	let totalFUT_USDT = 0
	let totalEARN_USDT = 0
	const tdBalanceStyle = { width: "30%" }

	// Получение строк таблиц
	const getRowTable = (
		balanceArray: any,
		nameList: string,
		param1: string,
		param2: string
	) => {
		let listItems: any = (
			<tr>
				<td colSpan={5}>{CONSTANTS.ERROR_TEXT}</td>
			</tr>
		)
		if (
			Array.isArray(currentCourses) &&
			currentCourses.length !== 0 &&
			balanceArray &&
			balanceArray.length !== 0 &&
			typeof balanceArray !== "string"
		) {
			listItems = balanceArray.map((item: any, index: number) => {
				const assetName = item.currency
				const total = +item[param1] + +item[param2]
				// пропускаем нулевой баланс валюты на аккаунте
				if (total === 0) return null

				// Расчет суммы баланса по аккаунту
				if (nameList === "SPOT")
					totalSPOT_USDT += +getValuationUSDT(currentCourses, assetName, total)
				else if (nameList === "P2P")
					totalP2P_USDT += +getValuationUSDT(currentCourses, assetName, total)
				else if (nameList === "FUT")
					totalFUT_USDT += +getValuationUSDT(currentCourses, assetName, total)
				else if (nameList === "EARN")
					totalEARN_USDT += +getValuationUSDT(currentCourses, assetName, total)

				return (
					<tr key={index}>
						<td style={tdBalanceStyle}></td>
						<td style={tdBalanceStyle}>
							<span className="icon-pay-dots p-1">
								<img
									src={getUrlIcon("iconCurrencyByName", assetName)}
									className="ml-1"
									alt="-"
									title={assetName}
								/>
								{assetName}
							</span>
						</td>
						{valuationUSDT ? (
							<>
								<td>{parseFloat(item[param1]).toFixed(6)}</td>
								<td>{parseFloat(item[param2]).toFixed(6)}</td>
								<td>{parseFloat(total.toString()).toFixed(6)}</td>
							</>
						) : (
							<>
								<td>
									{getValuationUSDT(currentCourses, assetName, item[param1])}
								</td>
								<td>
									{getValuationUSDT(currentCourses, assetName, item[param2])}
								</td>
								<td>{getValuationUSDT(currentCourses, assetName, total)}</td>
							</>
						)}
					</tr>
				)
			})
		}
		return listItems
	}

	const rowsSpotBalance: any = getRowTable(
		balances.spotBalance,
		"SPOT",
		"available",
		"frozen"
	)
	const rowsP2PBalance: any = getRowTable(
		balances.p2pBalance,
		"P2P",
		"available",
		"frozen"
	)
	const rowsFutBalance: any = getRowTable(
		balances.futBalance,
		"FUT",
		"available",
		"frozen"
	)
	const rowsEarnBalance: any = getRowTable(
		balances.earnBalance,
		"EARN",
		"available",
		"frozen"
	)

	const summUSDT =
		totalSPOT_USDT + totalP2P_USDT + totalEARN_USDT + totalFUT_USDT
	const lockedUSDT = Number(
		getValuationUSDT(currentCourses, "BTC", balances.lockedData)
	)
	const requestHeader = ""

	return (
		<div className="container">
			<div className="row d-flex justify-content-between mb-3">
				<button
					className="btn btn-outline-warning btn-sm"
					onClick={() => {
						if (requestHeader !== null) {
							const objParams = {
								userId,
								exchange: objExchange.name,
								exchangeId: objExchange.id,
								shortName: objExchange.shortName,
							}
							getBalances(objParams)
						} else {
							handlerPopupWindow(STYLES.WARNING, CONSTANTS.COOKIE_EMPTY)
							startModalAlert()
						}
					}}
				>
					Get Balances
				</button>
				{/* Locked Balances */}
				<div className="col-8">
					<span>{`Total balances: $${summUSDT.toFixed(2)}`}</span>
					{objExchange.shortName === "BN" ? (
						<span>
							{valuationUSDT
								? ` | Locked: ${Number(balances.lockedData).toFixed(8)} BTC`
								: ` | Locked: $${lockedUSDT.toFixed(2)} | Free: $${(
										summUSDT - lockedUSDT
								  ).toFixed(2)}`}
						</span>
					) : null}
				</div>
				{valuationUSDT ? (
					<button
						className="btn btn-outline-info btn-sm ml-3"
						onClick={() => changeValuation(!valuationUSDT)}
					>
						USDT
					</button>
				) : (
					<button
						className="btn btn-outline-success btn-sm ml-3"
						onClick={() => changeValuation(!valuationUSDT)}
					>
						Asset
					</button>
				)}
			</div>
			<div className="row">
				<Scrollbar style={scrollStyle}>
					{/* Spot Balance */}
					<table className="table table-hover table-striped table-sm">
						<thead>
							<tr className="table-info">
								<th style={tdBalanceStyle} className="text-left">
									Spot Balance
								</th>
								<th style={tdBalanceStyle}>Asset | Crypto</th>
								<th>Free</th>
								<th>Freeze</th>
								<th>Total</th>
							</tr>
						</thead>
						<tbody>{rowsSpotBalance}</tbody>
						<tfoot>
							<tr>
								<td className="text-left">
									<button
										className="btn btn-outline-info btn-sm"
										disabled={objExchange.shortName === "BN" ? false : true}
										onClick={() => {
											if (requestHeader !== null) {
												const objParams = {
													userId,
													exchange: objExchange.name,
													shortName: objExchange.shortName,
													toNameAccount: "SPOT",
												}
												transferAsset(objParams)
											} else {
												handlerPopupWindow(STYLES.WARNING, CONSTANTS.COOKIE_EMPTY)
												startModalAlert()
											}
										}}
									>
										Transfer USDT to P2P
									</button>
								</td>
								<td colSpan={3}></td>
								{valuationUSDT ? (
									<td>--</td>
								) : (
									<td>{totalSPOT_USDT.toFixed(2)}</td>
								)}
							</tr>
						</tfoot>
					</table>
					{/* P2P Balance */}
					<table className="table table-hover table-striped table-sm">
						<thead>
							<tr className="table-primary">
								<th style={tdBalanceStyle} className="text-left">
									P2P Balance
								</th>
								<th style={tdBalanceStyle}>Asset | Crypto</th>
								<th>Free</th>
								<th>Freeze</th>
								<th>Total</th>
							</tr>
						</thead>
						<tbody>{rowsP2PBalance}</tbody>
						<tfoot>
							<tr>
								<td className="text-left">
									<button
										className="btn btn-outline-primary btn-sm"
										disabled={objExchange.shortName === "BN" ? false : true}
										onClick={() => {
											if (requestHeader !== null) {
												const objParams = {
													userId,
													exchange: objExchange.name,
													shortName: objExchange.shortName,
													toNameAccount: "P2P",
													// requestHeader,
												}
												transferAsset(objParams)
											} else {
												handlerPopupWindow(STYLES.WARNING, CONSTANTS.COOKIE_EMPTY)
												startModalAlert()
											}
										}}
									>
										Transfer Assets to Spot
									</button>
								</td>
								<td colSpan={3}></td>
								{valuationUSDT ? <td>--</td> : <td>{totalP2P_USDT.toFixed(2)}</td>}
							</tr>
						</tfoot>
					</table>
					{/* Fut Balance */}
					{objExchange.shortName === "BN" ||
					objExchange.shortName === "BT" ||
					objExchange.shortName === "HB" ? (
						<table className="table table-hover table-striped table-sm">
							<thead>
								<tr className="table-success">
									<th style={tdBalanceStyle} className="text-left">
										Fut Balance
									</th>
									<th style={tdBalanceStyle}>Asset | Crypto</th>
									<th>Free</th>
									<th>Profit</th>
									<th>Total</th>
								</tr>
							</thead>
							<tbody>{rowsFutBalance}</tbody>
							<tfoot>
								<tr>
									<td colSpan={4}></td>
									{valuationUSDT ? (
										<td>--</td>
									) : (
										<td>{totalFUT_USDT.toFixed(2)}</td>
									)}
								</tr>
							</tfoot>
						</table>
					) : null}
					{/* Earn Balance */}
					{objExchange.shortName !== "BN" ? null : (
						<table className="table table-hover table-striped table-sm">
							<thead>
								<tr className="table-warning text-dark">
									<th style={tdBalanceStyle} className="text-left">
										Earn Balance
									</th>
									<th style={tdBalanceStyle}>Asset | Crypto</th>
									<th>Nothing</th>
									<th>Locked</th>
									<th>Total</th>
								</tr>
							</thead>
							<tbody>{rowsEarnBalance}</tbody>
							<tfoot>
								<tr>
									<td colSpan={4}></td>
									{valuationUSDT ? (
										<td>--</td>
									) : (
										<td>{totalEARN_USDT.toFixed(2)}</td>
									)}
								</tr>
							</tfoot>
						</table>
					)}
				</Scrollbar>
			</div>
		</div>
	)
}
