import React from "react"
import Scrollbar from "react-scrollbars-custom"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import {
	faDownload,
	faHourglassHalf,
	faPercent,
	faRocket,
	faSortAmountUp,
	faSortAmountDownAlt,
} from "@fortawesome/free-solid-svg-icons"
import { IAdditionalServices } from "../types"
import { CONSTANTS } from "../constants"

export const ReportAppWS: React.FC<IAdditionalServices> = props => {
	const {
		userId,
		getDataTickers,
		getFundingRates,
		fundingRates,
		scrollStyle,
	} = props
	const startState = {
		timeVisible: false,
		sorting: { sortName: "BN", sortStatus: false, sortType: "up" },
	}

	const [stateProps, handlerState] = React.useState(startState)

	const getTimeFunc = (nextFundingTime: any) => {
		let msgTime = "-"
		if (!isNaN(nextFundingTime)) {
			const duration: any = nextFundingTime - Date.now()
			let seconds: any = (duration / 1000) % 60
			let minutes: any = (duration / (1000 * 60)) % 60
			let hours: any = (duration / (1000 * 60 * 60)) % 24

			hours = hours < 10 ? "0" + hours : hours
			minutes = minutes < 10 ? "0" + minutes : minutes
			seconds = seconds < 10 ? "0" + seconds : seconds

			msgTime =
				// tslint:disable-next-line: radix
				parseInt(hours) + ":" + parseInt(minutes) + ":" + parseInt(seconds)
		}
		return msgTime
	}

	const getRateProps = (arr: any, name: any) => {
		const result: any = { currentRate: 0, predictedRate: 0, nextTime: 0 }
		for (let k = 0; k < arr.length; k++) {
			if (arr[k].exchangeName === name) {
				result.cR = isNaN(+arr[k].rate) ? 0 : +arr[k].rate.toFixed(4)
				result.pR = arr[k].predictedRate
				result.nextTime = getTimeFunc(arr[k].nextFundingTime)
			}
		}
		return result
	}

	const getArraySorted = (arr: any, sortObj: any) => {
		const { sortName, sortStatus, sortType } = sortObj
		const arraySorted = arr.sort((a: any, b: any) => {
			if (sortStatus) {
				if (sortName !== "Symbol" && sortType === "up") {
					if (Number(a[sortName].cR) > Number(b[sortName].cR)) return -1
					if (Number(a[sortName].cR) < Number(b[sortName].cR)) return 1
				} else if (sortName !== "Symbol" && sortType === "down") {
					if (Number(a[sortName].cR) < Number(b[sortName].cR)) return -1
					if (Number(a[sortName].cR) > Number(b[sortName].cR)) return 1
				} else if (sortName === "Symbol" && sortType === "up") {
					if (a.symbol > b.symbol) return -1
					if (a.symbol < b.symbol) return 1
				} else if (sortName === "Symbol" && sortType === "down") {
					if (a.symbol < b.symbol) return -1
					if (a.symbol > b.symbol) return 1
				}
			}
			return 0
		})
		return arraySorted
	}

	const getClassName = (rate: any) => {
		const prefix = "table-"
		const c1 = "danger"
		const c2 = "success"
		let classNameStyle = prefix
		if (+rate > 0) classNameStyle = prefix + c1
		else if (+rate < 0) classNameStyle = prefix + c2
		return classNameStyle
	}

	const ratesNormalized = fundingRates.map((item: any) => {
		return {
			symbol: item.symbol,
			logo: item.symbolLogo,
			price: item.uPrice,
			BN: getRateProps(item.uMarginList, "Binance"),
			KX: getRateProps(item.uMarginList, "OKX"),
			BT: getRateProps(item.uMarginList, "Bybit"),
			GT: getRateProps(item.uMarginList, "Gate"),
			BG: getRateProps(item.uMarginList, "Bitget"),
			CN: getRateProps(item.uMarginList, "CoinEx"),
			HB: getRateProps(item.uMarginList, "Huobi"),
			BX: getRateProps(item.uMarginList, "BingX"),
			MG: getRateProps(item.uMarginList, "MexcGlobal"),
		}
	})

	const ratesSorted = getArraySorted(ratesNormalized, stateProps.sorting)

	const sortIconStyle = { marginLeft: "5px", cursor: "pointer" }
	const namesTH = [
		"Symbol",
		"BN",
		"HB",
		"KX",
		"BT",
		"MG",
		"KC",
		"GT",
		"BG",
		"CN",
		"BX",
		"XT",
	]

	const listRates =
		fundingRates.length === 0 ? (
			<tr>
				<td colSpan={namesTH.length + 2}>{CONSTANTS.ERROR_TEXT}</td>
			</tr>
		) : (
			ratesSorted.map((item: any, index: number) => {
				return (
					<tr key={index}>
						<td>{index + 1}</td>
						<td className="text-left" style={{ width: "120px" }}>
							{item.price}
						</td>
						<td className="text-left" style={{ width: "120px" }}>
							<img
								src={item.logo}
								alt={item.symbol}
								style={{ width: "20px", height: "20px" }}
							/>
							{"  " + item.symbol}
						</td>
						{stateProps.timeVisible ? (
							<>
								<td>{item.BN.nextTime}</td>
								<td>{item.KX.nextTime}</td>
								<td>{item.BT.nextTime}</td>
								<td>{item.GT.nextTime}</td>
								<td>{item.BG.nextTime}</td>
								<td>{item.CN.nextTime}</td>
								<td>{item.HB.nextTime}</td>
								<td>{item.BX.nextTime}</td>
								<td>{item.MG.nextTime}</td>
							</>
						) : (
							<>
								<td className={getClassName(item.BN.cR)}>{item.BN.cR}</td>
								<td title={item.KX.pR} className={getClassName(item.KX.cR)}>
									{item.KX.cR}
								</td>
								<td className={getClassName(item.BT.cR)}>{item.BT.cR}</td>
								<td title={item.GT.pR} className={getClassName(item.GT.cR)}>
									{item.GT.cR}
								</td>
								<td className={getClassName(item.BG.cR)}>{item.BG.cR}</td>
								<td className={getClassName(item.CN.cR)}>{item.CN.cR}</td>
								<td title={item.HB.pR} className={getClassName(item.HB.cR)}>
									{item.HB.cR}
								</td>
								<td className={getClassName(item.BX.cR)}>{item.BX.cR}</td>
								<td className={getClassName(item.MG.cR)}>{item.MG.cR}</td>
							</>
						)}
					</tr>
				)
			})
		)

	return (
		<div className="container">
			<div className="row">
				<Scrollbar style={scrollStyle}>
					<table className="table table-hover table-striped table-sm">
						<thead>
							<tr>
								<th colSpan={2} scope="col" className="text-left">
									<button
										className="btn btn-outline-warning btn-sm"
										title="getDataTickers"
										// disabled
										onClick={() => {
											const objParams = { userId, arrExchanges: [] }
											getDataTickers(objParams)
										}}
									>
										<FontAwesomeIcon icon={faRocket} />
									</button>
									<button
										className="btn btn-outline-success btn-sm"
										title="getFundingRates(userId)"
										onClick={() => {
											const objParams = { userId, arrExchanges: [] }
											getFundingRates(objParams)
										}}
									>
										<FontAwesomeIcon icon={faDownload} />
									</button>
									<button
										className={`btn btn-outline-${
											stateProps.timeVisible ? "info" : "danger"
										} btn-sm`}
										title="timeVisible"
										onClick={() => {
											handlerState({
												...stateProps,
												timeVisible: !stateProps.timeVisible,
											})
										}}
									>
										{stateProps.timeVisible ? (
											<FontAwesomeIcon icon={faPercent} />
										) : (
											<FontAwesomeIcon icon={faHourglassHalf} />
										)}
									</button>
								</th>
								{namesTH.map((item: any, index: number) => {
									const { sortName, sortStatus, sortType } = stateProps.sorting
									return (
										<th
											key={index}
											scope="col"
											style={{ cursor: "pointer" }}
											className={item === "Symbol" ? "text-left" : ""}
										>
											<span
												onClick={() => {
													handlerState({
														...stateProps,
														sorting: {
															...stateProps.sorting,
															sortName: item,
															sortStatus: !stateProps.sorting.sortStatus,
														},
													})
												}}
											>
												{item}
											</span>
											{sortName === item && sortStatus ? (
												<span
													className="text-warning"
													title={sortType}
													style={sortIconStyle}
													onClick={() => {
														handlerState({
															...stateProps,
															sorting: {
																...stateProps.sorting,
																sortName: item,
																sortType:
																	stateProps.sorting.sortType === "up" ? "down" : "up",
															},
														})
													}}
												>
													<FontAwesomeIcon
														icon={
															sortType === "up" ? faSortAmountDownAlt : faSortAmountUp
														}
													/>
												</span>
											) : null}
										</th>
									)
								})}
							</tr>
						</thead>
						<tbody>{listRates}</tbody>
					</table>
				</Scrollbar>
			</div>
		</div>
	)
}
