import * as React from "react"
import $ from "jquery"
import { CONSTANTS, STYLES } from "../constants"
import { IFilterP2POrders } from "../types"
import {
	startModalAlert,
	getArrayCurrenciesFiltered,
	resetHighlightItem,
	getTickerName,
	handlerPriceTickers,
	getPriceMasked,
	getUrlIcon,
} from "../common"

export const FilterP2POrders: React.FC<IFilterP2POrders> = props => {
	const {
		userProps,
		objExchange,
		arrPayTypes,
		currentCourses,
		getListOption,
		getP2POrders,
		handlerPopupWindow,
		handlerUserProfile,
	} = props

	const { userId, userPayTypesList, sellingPriceUSDT } = userProps
	const startState = {
		fiat: "RUB",
		asset: "USDT",
		tradeType: "BUY",
		priceAssetFiat: "",
		priceCurrencyUSDT: "",
		transAmount: "500",
		payTypeName: "",
		quantityPages: "20",
		checkboxStatus: false,
		payTypeList: [],
	}
	const [p2pFilter, handlerP2PFilter] = React.useState(startState)

	React.useEffect(() => {
		handlerP2PFilter({
			...p2pFilter,
			payTypeList: userPayTypesList,
		})
		// eslint-disable-line react-hooks/exhaustive-deps
	}, [userPayTypesList, handlerP2PFilter])

	// adding and removing payType
	const hendlerPayTypeList = (
		state: any,
		payType: string,
		flag: string
	) => {
		const arrPayments = state.payTypeList.slice()
		if (flag === "removePayment") {
			for (let j = 0; j < arrPayments.length; j++) {
				if (arrPayments[j] === payType) arrPayments.splice(j, 1)
			}
		} else {
			// flag === "addPayment"
			if (arrPayments.length === 5) {
				handlerPopupWindow(
					STYLES.WARNING,
					`${objExchange.shortName}: ${CONSTANTS.LIMIT_PAYTYPES}`
				)
				startModalAlert()
			} else arrPayments.push(payType)
		}
		// обновление reduxState
		handlerUserProfile(objExchange.name, "userPayTypeList", arrPayments)
		return arrPayments
	}

	const fiatCurrency = p2pFilter.fiat === "USD" ? "USDT" : p2pFilter.fiat

	const arrayAssetsFiltered = getArrayCurrenciesFiltered(
		objExchange.id,
		"coin"
	)

	const arrayFiatsFiltered = getArrayCurrenciesFiltered(
		objExchange.id,
		"fiat"
	)

	const listQuantityOptions = getListOption(
		CONSTANTS.QUANTITY_PAGES,
		"quantityPages"
	)

	const listFiatOptions = arrayFiatsFiltered.map(
		(item: any, index: number) => {
			return (
				<option key={index} value={item.currency}>
					{item.currency}
				</option>
			)
		}
	)

	const listAssetButtons = arrayAssetsFiltered.map(
		(item: any, index: number) => {
			const classButton =
				item.currency === "USDT"
					? "btn btn-outline-warning active"
					: "btn btn-outline-warning"

			return (
				<button
					name={item.currency}
					key={index}
					type="button"
					className={classButton}
				>
					{/* {item.currency} */}
					<img
						style={{ width: "20px", height: "20px" }}
						src={item.iconUrl}
						alt="*"
						title={item.currency}
						onClick={(ev: any) => {
							resetHighlightItem(
								ev.target.parentElement,
								$(`#assetType-${objExchange.shortName} button`)
							)
							handlerP2PFilter({
								...p2pFilter,
								asset: item.currency,
								priceAssetFiat: handlerPriceTickers(
									getTickerName("tickerAssetFiat", item.currency, fiatCurrency),
									currentCourses
								),
								priceCurrencyUSDT: handlerPriceTickers(
									getTickerName("tickerCurrencyUSDT", item.currency, "USDT"),
									currentCourses
								),
							})
						}}
					/>
				</button>
			)
		}
	)

	const listOptionsPayTypes = arrPayTypes.map(
		(item: any, index: number) => {
			return (
				<option key={index} value={item.payType}>
					{item.payType}
				</option>
			)
		}
	)

	const listIconPayType =
		p2pFilter.payTypeList.length === 0 ? (
			<span>All payTypes</span>
		) : (
			arrPayTypes.map((item: any, index: number) => {
				let elem = null
				for (let i = 0; i < p2pFilter.payTypeList.length; i++) {
					if (p2pFilter.payTypeList[i] === item.payType) {
						elem = (
							<span key={index} className="icon-pay-dots-filter">
								<img
									src={getUrlIcon("iconPaymentByID", item.id)}
									alt="*"
									title={item.payType}
									id={item.payType}
									onClick={(ev: any) =>
										handlerP2PFilter({
											...p2pFilter,
											payTypeList: hendlerPayTypeList(
												p2pFilter,
												item.payType,
												"removePayment"
											),
										})
									}
								/>
							</span>
						)
					}
				}
				return elem
			})
		)

	return (
		<div className="container">
			<div className="row justify-content-between mb-3">
				{/* tradeType */}
				<div
					id={`tradeType-${objExchange.shortName}`}
					className="btn-group btn-group-sm col-2"
					role="group"
					aria-label="Basic example"
				>
					<button
						name="BUY"
						type="button"
						className="btn btn-outline-success active"
						onClick={(ev: any) => {
							resetHighlightItem(
								ev.target,
								$(`#tradeType-${objExchange.shortName} button`)
							)
							// handlerFilterDetails(objExchange.name, "tradeType", ev.target.name)
							handlerP2PFilter({
								...p2pFilter,
								tradeType: ev.target.name,
							})
						}}
					>
						Buy
					</button>
					<button
						name="SELL"
						type="button"
						className="btn btn-outline-danger"
						onClick={(ev: any) => {
							resetHighlightItem(
								ev.target,
								$(`#tradeType-${objExchange.shortName} button`)
							)
							// handlerFilterDetails(objExchange.name, "tradeType", ev.target.name)
							handlerP2PFilter({
								...p2pFilter,
								tradeType: ev.target.name,
							})
						}}
					>
						Sell
					</button>
				</div>
				{/* listAssetButtons */}
				<div
					id={`assetType-${objExchange.shortName}`}
					className="btn-group btn-group-sm col-4"
					role="group"
					aria-label="Basic example"
				>
					{listAssetButtons}
				</div>

				{p2pFilter.priceAssetFiat === "" ? (
					<div className="col-4">{null}</div>
				) : (
					<div className="col-4">
						<span className="mr-3">
							<span className="icon-pay-dots ml-2">
								{p2pFilter.asset === "USDT" && fiatCurrency === "RUB" ? null : (
									<>
										<img
											src={getUrlIcon("iconCurrencyByName", p2pFilter.asset)}
											alt="*"
											title={p2pFilter.asset}
										/>
										<img
											src={getUrlIcon("iconCurrencyByName", "USDT")}
											alt="*"
											title={"USDT"}
										/>
										{"$ " + getPriceMasked(p2pFilter.priceCurrencyUSDT)}
									</>
								)}
							</span>
							<span className="icon-pay-dots ml-2">
								<img
									src={getUrlIcon("iconCurrencyByName", p2pFilter.asset)}
									alt="*"
									title={p2pFilter.asset}
								/>
								<img
									src={getUrlIcon("iconCurrencyByName", p2pFilter.fiat)}
									alt="*"
									title={p2pFilter.fiat}
								/>
								{"₽ " + getPriceMasked(p2pFilter.priceAssetFiat)}
							</span>
						</span>
					</div>
				)}

				<div className="col-2 text-left">{listIconPayType}</div>
			</div>

			<div className="row mb-3">
				<div className="col-6">
					<div className="input-group input-group-sm">
						{/* Select Summ */}
						<div className="input-group-prepend">
							<span className="input-group-text" id="fiatCurrency">
								{fiatCurrency}
							</span>
						</div>
						<input
							className="form-control form-control-sm mr-1"
							type="number"
							step="1000"
							placeholder="Summ (optional)"
							aria-describedby="fiatCurrency"
							value={p2pFilter.transAmount === null ? "" : p2pFilter.transAmount}
							onChange={(ev: any) =>
								// handlerFilterDetails(objExchange.name,"transAmount",ev.target.value)
								handlerP2PFilter({
									...p2pFilter,
									transAmount: ev.target.value,
								})
							}
						/>
						{/* Select quantityPages */}
						<select
							id="quantityPages"
							className="custom-select mr-1 form-control-sm"
							value={
								p2pFilter.quantityPages === null ? "" : p2pFilter.quantityPages
							}
							onChange={(ev: any) => {
								handlerP2PFilter({
									...p2pFilter,
									quantityPages: ev.target.value,
								})
							}}
						>
							{listQuantityOptions}
						</select>
						{/* select Fiat */}
						<select
							id="fiat"
							className="custom-select mr-1 form-control-sm"
							value={p2pFilter.fiat === null ? "" : p2pFilter.fiat}
							onChange={(ev: any) => {
								handlerP2PFilter({
									...p2pFilter,
									fiat: ev.target.value,
								})
							}}
						>
							{listFiatOptions}
						</select>
						<div className="input-group-append">
							<button
								className="btn btn-sm btn-info"
								type="button"
								id="button-addon2"
								onClick={() => {
									const requestHeader = ""
									if (requestHeader !== null) {
										const objOrder = {
											userId,
											exchangeId: objExchange.id,
											exchangeName: objExchange.name,
											shortName: objExchange.shortName,
											objParams: {
												asset: p2pFilter.asset,
												fiat: p2pFilter.fiat,
												arrPayments: p2pFilter.payTypeList,
												sideType: p2pFilter.tradeType,
												quantityPages: p2pFilter.quantityPages,
												amount: p2pFilter.transAmount,
												page: 1,
												rows: 20,
											},
										}
										// console.log(objOrder)
										getP2POrders(objOrder)
									} else {
										handlerPopupWindow(
											STYLES.WARNING,
											`${objExchange.shortName}: ${CONSTANTS.COOKIE_EMPTY}`
										)
										startModalAlert()
									}
								}}
							>
								UPD
							</button>
						</div>
					</div>
				</div>

				<div className="col-2">
					{p2pFilter.fiat === "RUB" && sellingPriceUSDT !== 0
						? `AdvSell: $${sellingPriceUSDT}`
						: "--"}
				</div>

				{/* checkbox Merchant or Online only */}
				<div className="col-2">
					<div className="form-check">
						<input
							className="form-check-input"
							type="checkbox"
							id={`checkboxStatus-${objExchange.shortName}`}
							onChange={() =>
								// handlerFilterDetails(objExchange.name,"checkboxStatus",!p2pFilter.checkboxStatus)
								handlerP2PFilter({
									...p2pFilter,
									checkboxStatus: !p2pFilter.checkboxStatus,
								})
							}
						/>
						<label
							className="form-check-label"
							htmlFor={`checkboxStatus-${objExchange.shortName}`}
						>
							Online only
						</label>
					</div>
				</div>

				{/* select payTypes */}
				<div className="input-group input-group-sm col-2">
					<select
						id="p2pPayType"
						className="custom-select mr-1 form-control-sm"
						value={p2pFilter.payTypeName === null ? "" : p2pFilter.payTypeName}
						onChange={(ev: any) => {
							handlerP2PFilter({
								...p2pFilter,
								payTypeName: ev.target.value,
								payTypeList:
									ev.target.value === ""
										? []
										: hendlerPayTypeList(p2pFilter, ev.target.value, "addPayment"),
							})
						}}
					>
						<option value="">All Payments</option>
						{listOptionsPayTypes}
					</select>
				</div>
			</div>
		</div>
	)
}
