import * as React from "react"
import Scrollbar from "react-scrollbars-custom"
import Switch from "@material-ui/core/Switch"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import {
	faEdit,
	faEyeSlash,
	faInfoCircle,
	faClock,
} from "@fortawesome/free-solid-svg-icons"
import { CONSTANTS, STYLES } from "../constants"
import { IListUserAdvs } from "../types"
import {
	startModalAlert,
	getPriceMasked,
	getTimeDate,
	getTickerName,
	handlerPriceTickers,
	getUrlIcon,
	getPercent,
	replace000ToK,
	getValuationUSDT,
} from "../common"

export const ListUserAdvs: React.FC<IListUserAdvs> = props => {
	const {
		advs,
		userId,
		objExchange,
		scrollStyle,
		currentCourses,
		changeAdvStatus,
		getEditableAdv,
		handlerPopupWindow,
	} = props

	const { id, name, shortName, advDetail } = objExchange

	const [state, setState] = React.useState({
		switcherAllAdvs: true,
	})

	const handleChangeAllStatus = (
		e: React.ChangeEvent<HTMLInputElement>
	) => {
		setState({ ...state, [e.target.name]: e.target.checked })
	}

	const getValuationByAsset = (firstAsset: string, secondAsset: string) => {
		let courseBTCRUB = 0
		let courseBTCUSDT = 0
		let courseUSDTRUB = 0
		if (Array.isArray(currentCourses) && currentCourses.length !== 0) {
			for (let i = 0; i < currentCourses.length; i++) {
				if (currentCourses[i].asset === firstAsset)
					courseBTCUSDT = currentCourses[i].courseUSDT
				if (currentCourses[i].asset === secondAsset)
					courseUSDTRUB = currentCourses[i].courseUSDT
			}
		}
		courseBTCRUB = courseBTCUSDT * courseUSDTRUB
		return courseBTCRUB
	}

	const courseBTCRUB = getValuationByAsset("BTC", "RUB")
	const paymentStyles = { width: "auto" }
	if (shortName === "BG") paymentStyles.width = "250px"
	else if (shortName === "KX") paymentStyles.width = "145px"
	const classSwitcher =
		state.switcherAllAdvs === true ? "success" : "danger"

	const ArrayAdvNumbers: string[] = []
	const listOrders =
		advs && advs.length !== 0 ? (
			advs.map((item: any, index: number) => {
				ArrayAdvNumbers.push(item.advId)
				// подсветка BUY и SELL ордеров
				const classTradeType = item.tradeType === "BUY" ? "success" : "danger"
				const advSwitcher = item.advStatus

				let iconAmount: any = null
				const surplusAmount =
					item.asset === "BTC"
						? Number(item.volume).toFixed(5)
						: Number(item.volume).toFixed(2)

				const volumeUSDT: any = Number(
					getValuationUSDT(currentCourses, item.asset, surplusAmount)
				)

				let advURL = ""
				if (shortName === "BN") advURL = advDetail + item.advId

				// const fiatCurrency = item.fiat === "USD" ? "USDT" : item.fiat
				const fiatCurrency = item.fiat
				const priceAssetFiat = handlerPriceTickers(
					getTickerName("tickerAssetFiat", item.asset, item.fiat),
					currentCourses
				)
				const priceCurrencyUSDT = handlerPriceTickers(
					getTickerName("tickerCurrencyUSDT", item.asset, "USDT"),
					currentCourses
				)
				const priceRatio = getPercent(
					item.exchange,
					item.price,
					item.tradeType,
					priceAssetFiat,
					priceCurrencyUSDT
				)
				let classPriceRatio = "warning"
				if (+priceRatio > 0) classPriceRatio = "success"
				else if (+priceRatio < 0) classPriceRatio = "danger"

				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>
					)
				})

				// провека минимального размера суммы объявления
				if (item.tradeType === "SELL" && shortName === "BN") {
					if (
						(item.asset === "USDT" && +surplusAmount < 10) ||
						(item.asset === "BTC" && +surplusAmount * courseBTCRUB < 500) ||
						(item.asset === "RUB" && +surplusAmount < 500)
					) {
						iconAmount = (
							<FontAwesomeIcon
								className="text-danger mr-2"
								title="Low limit"
								icon={faEyeSlash}
							/>
						)
					}
				}

				return (
					<tr key={index}>
						<td>{index + 1}</td>
						<td>
							<div className={`table-${classTradeType} icon-pay-dots p-1`}>
								{item.tradeType}
								<img
									src={getUrlIcon("iconCurrencyByName", item.asset)}
									className="ml-1"
									alt="-"
									title={item.asset}
								/>
								{`${item.asset} / ${fiatCurrency}`}
							</div>
						</td>
						<td className="tbl-header text-right">
							<div>
								{iconAmount}
								{`≈ $ ${volumeUSDT} | `}
								{item.asset === "SHIB" || item.asset === "RUB"
									? replace000ToK(+surplusAmount)
									: surplusAmount}
								{" | "}
								{item.asset === "SHIB" || item.asset === "RUB"
									? replace000ToK(Number(item.amount))
									: getPriceMasked(item.amount)}
							</div>
							<span>
								{getPriceMasked(item.minLimit) +
									" - " +
									getPriceMasked(item.maxLimit) +
									" " +
									fiatCurrency}
							</span>
						</td>
						<td className="tbl-header text-right">
							<span>{`${getUrlIcon("FiatSymbol", fiatCurrency)} ${getPriceMasked(
								item.price
							)}`}</span>
							<span className={`text-${classPriceRatio}`}>
								{`${getPriceMasked(priceRatio)}%`}
							</span>
						</td>
						<td>{paymentDots}</td>
						<td className="tbl-header text-right">
							<span>{getTimeDate(item.createAt)}</span>
							<span>
								{item.updateAt === null ? "--/--/--" : getTimeDate(item.updateAt)}
							</span>
						</td>
						<td className="text-right">
							<span>{item.advId}</span>
							<div>
								{item.timeLimit !== "0" ? (
									<>
										<FontAwesomeIcon
											icon={faClock}
											style={{ cursor: "pointer" }}
											className="text-info"
											title="timeLimit"
										/>
										{` ${item.timeLimit} minutes`}
									</>
								) : null}
								<Switch
									// disabled
									checked={advSwitcher}
									size="small"
									onChange={() => {
										// const objAdv = {
										// 	userId,
										// 	exchangeId: id,
										// 	exchangeName: name,
										// 	shortName,
										// 	arrayAdvNumbers: [item.advId],
										// 	advStatus: advSwitcher,
										// }
										// changeAdvStatus(objAdv)
									}}
								/>
								{shortName === "BN" ? (
									<FontAwesomeIcon
										icon={faEdit}
										style={{ cursor: "pointer" }}
										className="text-success ml-2"
										title="Edit adv"
										onClick={() => {
											getEditableAdv({
												userId,
												exchangeId: id,
												exchangeName: name,
												shortName,
												advIdNumber: item.advId,
											})
										}}
									/>
								) : null}
								<a
									href={advURL}
									target="_blank"
									rel="noopener noreferrer"
									className="text-warning ml-2"
									title="advDetail"
								>
									<FontAwesomeIcon icon={faInfoCircle} />
								</a>
							</div>
						</td>
					</tr>
				)
			})
		) : (
			<tr>
				<td colSpan={7}>{CONSTANTS.ERROR_TEXT}</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">
									<span>Side | Ticker</span>
								</th>
								<th scope="col" className="tbl-header text-right">
									<span>availableSumm | tradedVolume</span>
									<span>limitSumm</span>
								</th>
								<th scope="col" className="text-right">
									<span>Price | Dev, %</span>
								</th>
								<th scope="col" style={paymentStyles}>
									<span>Payment</span>
								</th>
								<th scope="col" className="text-right">
									<span>Created | Updated</span>
								</th>
								<th scope="col" className="text-right" style={{ width: "200px" }}>
									<span>IdNumber | Action</span>
									<div>
										<Switch
											disabled
											checked={state.switcherAllAdvs}
											size="small"
											onChange={(ev: any) => {
												handleChangeAllStatus(ev)
												const requestHeader = ""
												if (requestHeader !== null) {
													const objAdv = {
														userId,
														exchangeId: id,
														exchangeName: name,
														shortName,
														arrayAdvNumbers: ArrayAdvNumbers,
														advStatus: state.switcherAllAdvs ? 3 : 1,
													}
													changeAdvStatus(objAdv)
												} else {
													handlerPopupWindow(STYLES.WARNING, CONSTANTS.COOKIE_EMPTY)
													startModalAlert()
												}
											}}
											color="secondary"
											name="switcherAllAdvs"
											// inputProps={{ "aria-label": "secondary checkbox" }}
										/>
										<span className={`text-${classSwitcher} ml-2`}>
											{state.switcherAllAdvs
												? "AllAdvsSwitchedON"
												: "AllAdvsSwitchedOFF"}
										</span>
									</div>
								</th>
							</tr>
						</thead>
						<tbody>{listOrders}</tbody>
					</table>
				</Scrollbar>
			</div>
		</div>
	)
}
