import * as React from "react"
import $ from "jquery"
import { COOKIE_ACTIVE_HOURS, CONSTANTS, STYLES } from "../constants"
import { SettingsUser, SettingsCookie, SettingsApp } from "."
import { ISettingsPanel } from "../types"
import {
	getTimeDate,
	getUrlIcon,
	startModalAlert,
	getDataFromLocalStorage,
	saveDataToLocalStorage,
	getUserPropsByExchange,
} from "../common"

export const SettingsPanel: React.FC<ISettingsPanel> = props => {
	const {
		userProfile,
		userOrderStatuses,
		scrollStyle,
		dataConstants,
		updateUser,
		updateItemDetails,
		handlerUserProfile,
		handlerFilterDetails,
		handlerPopupWindow,
		getGroupItems,
		checkOrderStatuses,
	} = props

	const { userProperties } = userProfile
	const { exchanges } = dataConstants

	// Получение отфильтрованного массива exchanges by status
	const exchangesFiltered = exchanges.filter((item: any) => {
		return item.status
	})

	const arrParams = exchangesFiltered.map((item: any, index: number) => {
		const nowDate = new Date()
		const diff = 3600000
		const userProps = getUserPropsByExchange(item.id, userProperties)
		const headerLS = getDataFromLocalStorage(
			`requestHeader_${item.shortName}`
		)
		const dateCookie = headerLS ? headerLS.timestamp : 0
		return {
			exchangeId: item.id,
			exchangeName: item.name,
			shortName: item.shortName,
			headerLS,
			dateCookie,
			dateApiKeys: userProps.dateApiKeys,
			h_now: Math.abs(+nowDate - dateCookie) / diff,
		}
	})

	const storageProps: any = {
		currentExchange: {
			exchangeId: arrParams[0].exchangeId,
			exchangeName: arrParams[0].exchangeName,
			shortName: arrParams[0].shortName,
			headerLS: arrParams[0].headerLS,
			dateCookie: arrParams[0].dateCookie,
			dateApiKeys: arrParams[0].dateApiKeys,
			h_now: arrParams[0].h_now,
		},
		cookieTextarea: "",
		typeRequest: "", // running, comleted, balances
		additionals: [],
		requestHeader: {},
	}

	const [objStorage, handlerStorage] = React.useState(storageProps)

	const {
		// exchangeId,
		exchangeName,
		shortName,
		headerLS,
		dateCookie,
		dateApiKeys,
		h_now,
	} = objStorage.currentExchange

	// парсинг значений requestHeader
	const getRequestHeaderFromString = (exchange: string, value: any) => {
		// преобразуем строку в массив по разделителю - перенос строки \n
		const arr = value.trim().split("\n")

		// получение значения обязательного поля по его наименованию
		const fetchRequireField = (nameField: string) => {
			let normalStr = null
			for (let i = 0; i < arr.length; i++) {
				if (arr[i].indexOf(nameField) !== -1) {
					normalStr = arr[i].split(": ")[1].replace(/(\r\n|\n|\r)/gm, "")
					// console.log(nameField + ": " + normalStr)
				}
			}
			return normalStr
		}

		// проверяем корректность заполнения
		const isRequestHeaderCorrect = (obj: any) => {
			let result = true
			for (const key in obj) {
				if (obj[key] === null) {
					result = false
					break
				}
			}
			return result
		}

		let objFields = {}
		if (exchange === "BN") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				csrftoken: fetchRequireField("csrftoken"),
				deviceInfo: fetchRequireField("device-info"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "HB") {
			// !!! куки забирать на странице spot-баланса
			objFields = {
				// token: fetchRequireField("hb-pro-token"),
				token: fetchRequireField("token"),
				cookie: fetchRequireField("cookie"),
				// fingerprint: "__",
				// traceId: fetchRequireField("trace_id"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "KX") {
			objFields = {
				authorization: fetchRequireField("authorization"),
				cookie: fetchRequireField("cookie"),
				devId: fetchRequireField("devid"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "BZ") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "GX") {
			objFields = {
				token: "",
				userAgent:
					"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36",
			}
		} else if (exchange === "BT") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				userAgent: fetchRequireField("user-agent"),
				usertoken: fetchRequireField("risktoken"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "PX") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				csrftoken: fetchRequireField("csrftoken"),
				deviceInfo: fetchRequireField("device-info"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "MG") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				// csrftoken: fetchRequireField("csrftoken"),
				// deviceInfo: fetchRequireField("device-info"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "KC") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "GT") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				csrftoken: fetchRequireField("csrftoken"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "BG") {
		} else if (exchange === "BX") {
			// !!! Для балансов куки забирать на странице Overview
			// https://bingx.com/en-us/assets/?tab=0
			// account-total-overview
			objFields = {
				appVersion: fetchRequireField("app_version:"),
				authorization: fetchRequireField("authorization"),
				deviceId: fetchRequireField("device_id"),
				sign: fetchRequireField("sign"),
				timestamp: fetchRequireField("timestamp"),
				traceId: fetchRequireField("traceid"),
				userAgent: fetchRequireField("user-agent"),
			}
		} else if (exchange === "CX") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				csrftoken: fetchRequireField("csrftoken"),
				deviceInfo: fetchRequireField("device-info"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "XG") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "CN") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				userAgent: fetchRequireField("user-agent"),
				authorization: fetchRequireField("authorization"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "BM") {
			objFields = {
				cookie: fetchRequireField("cookie"),
				userAgent: fetchRequireField("user-agent"),
				x_bm_client: fetchRequireField("x-bm-client"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "CM") {
			objFields = {
				// cookie: fetchRequireField("cookie"),
				authorization: fetchRequireField("authorization"),
				userAgent: fetchRequireField("user-agent"),
				timestamp: new Date().getTime(),
			}
		} else if (exchange === "XT") {
			objFields = {
				userAgent: fetchRequireField("user-agent"),
				token: fetchRequireField("token"),
				// authorization: fetchRequireField("authorization"),
				// cookie: fetchRequireField("cookie"),
				timestamp: new Date().getTime(),
			}
		}

		const requestHeader = isRequestHeaderCorrect(objFields)
			? objFields
			: null
		return requestHeader
	}

	const changeCurrentExchange = (exchangeId: string) => {
		const filteredCurrentExchange = arrParams.filter((item: any) => {
			return item.exchangeId === exchangeId
		})
		handlerStorage({
			...objStorage,
			currentExchange: filteredCurrentExchange[0],
		})
	}

	const checkSave = (nameRequest: string) => {
		const ff = objStorage.additionals.slice()
		const arr = ff.filter((item: any) => {
			return item.typeRequest === nameRequest
		})
		const result = arr.length === 0 || ff === undefined ? false : true
		return result
	}

	const handlerAdditionalsBX = (typeRequest: string) => {
		const newItem = {
			appVersion: objStorage.requestHeader.appVersion,
			authorization: objStorage.requestHeader.authorization,
			deviceId: objStorage.requestHeader.deviceId,
			sign: objStorage.requestHeader.sign,
			timestamp: objStorage.requestHeader.timestamp,
			traceId: objStorage.requestHeader.traceId,
			userAgent: objStorage.requestHeader.userAgent,
			typeRequest,
		}
		const arr = objStorage.additionals.slice()
		arr.push(newItem)
		handlerStorage({
			...storageProps,
			additionals: arr,
		})
	}

	const listNavExchanges = exchangesFiltered.map(
		(item: any, index: number) => {
			const activeItemClass =
				item.shortName === "BN" ? "nav-link active" : "nav-link"
			return (
				<li
					key={index}
					className="nav-item"
					title={item.name}
					onClick={() => {
						changeCurrentExchange(item.id)
					}}
				>
					<a
						className={activeItemClass}
						id={`settingsTab_${item.shortName}`}
						data-toggle="pill"
						href={`#settings_${item.shortName}`}
						role="tab"
						aria-controls={`settings_${item.shortName}`}
						aria-selected="true"
					>
						<span className="icon-pay-dots">
							<img
								src={getUrlIcon("logoExchange", item.shortName)}
								className="ml-1"
								alt="-"
							/>
							{item.shortName}
						</span>
					</a>
				</li>
			)
		}
	)

	const bingxFragment = (
		<div className="input-group mt-2">
			<div className="input-group-prepend">
				<button
					className="btn btn-outline-info"
					type="button"
					onClick={() => {
						handlerAdditionalsBX(objStorage.typeRequest)
						$(`#cookieTextarea${shortName}`).val("")
					}}
				>
					Save
				</button>
			</div>
			<select
				className="custom-select"
				id="typeRequestSelect"
				value={objStorage.typeRequest === null ? "" : objStorage.typeRequest}
				onChange={(ev: any) => {
					handlerStorage({
						...objStorage,
						typeRequest: ev.target.value,
					})
				}}
			>
				<option value="">Select Type</option>
				<option value="running">RequestHeader Running Orders</option>
				<option value="completed">RequestHeader Completed Orders</option>
				<option value="balances">RequestHeader Balances</option>
			</select>
		</div>
	)
	const bageClass = {
		d: "ml-2 badge-pill badge-danger",
		c: "ml-2 badge-pill badge-success",
	}

	const listSettingItems = (
		<div
			className="tab-pane fade show active"
			id={`settings_${shortName}`}
			role="tabpanel"
			aria-labelledby={`settingsTab_${shortName}`}
		>
			{/* Cookies */}
			<div className="row text-left mb-5">
				<div className="form-group col-6">
					<label htmlFor={`cookieTextarea${shortName}`}>
						{`Insert and Save your ${exchangeName} cookies`}
					</label>
					<textarea
						className="form-control"
						id={`cookieTextarea${shortName}`}
						rows={7}
						style={{ height: "70px" }}
						onChange={(ev: any) => {
							if (ev.target.value !== "") {
								const requestHeader = getRequestHeaderFromString(
									shortName,
									ev.target.value
								)
								handlerStorage({
									...objStorage,
									requestHeader: {},
								})
								if (requestHeader === null) {
									// показываем предупреждение и popup
									handlerPopupWindow(STYLES.WARNING, CONSTANTS.COOKIE_INVALID)
									startModalAlert()
								} else {
									handlerStorage({
										...objStorage,
										requestHeader,
									})
								}
							}
						}}
					></textarea>
					{shortName === "BX" ? bingxFragment : null}
					<button
						type="button"
						disabled={
							Object.keys(objStorage.requestHeader).length === 0 ? true : false
						}
						className="btn btn-primary mt-2"
						onClick={() => {
							saveDataToLocalStorage(`requestHeader_${shortName}`, {
								timestamp: new Date().getTime(),
							})
							if (shortName === "BX") {
								objStorage.requestHeader.additionals = objStorage.additionals
							}
							const objUser = {
								exchange: exchangeName,
								fieldChangeable: "requestHeader",
								id: userProfile.id,
								requestHeader: objStorage.requestHeader,
							}
							// обновляем данные в БД
							updateUser(objUser)
							// console.log(objUser)

							// очищаем поле
							$(`#cookieTextarea${shortName}`).val("")
							handlerStorage({
								...objStorage,
								requestHeader: {},
								additionals: [],
							})
						}}
					>
						{shortName === "GX" ? "UpdateToken" : "Insert"}
					</button>
					{shortName === "BX" ? (
						<>
							<span className={checkSave("running") ? bageClass.c : bageClass.d}>
								Unpaid Orders
							</span>
							<span
								className={checkSave("completed") ? bageClass.c : bageClass.d}
							>
								Completed Orders
							</span>
							<span className={checkSave("balances") ? bageClass.c : bageClass.d}>
								Balances
							</span>
						</>
					) : null}
				</div>
				<div className="form-group col-6">
					<p>LocaStorage Status</p>
					<ul>
						<li>
							Saved cookies:{" "}
							<span className={headerLS ? "text-success" : "text-danger"}>
								{headerLS ? "TRUE" : "FALSE"}
							</span>
						</li>
						<li>
							Date:{" "}
							{dateCookie ? (
								<span
									className={
										h_now > COOKIE_ACTIVE_HOURS ? "text-danger" : "text-success"
									}
								>
									{getTimeDate(dateCookie)}
								</span>
							) : null}
						</li>
					</ul>
				</div>
			</div>
			{/* apiKeys */}
			<div className="row text-left mb-5">
				<div className="col-6">
					<div className="form-group">
						<label className="publicKey">{`${exchangeName} API-Keys`}</label>
						<div className="input-group mb-3">
							<div className="input-group-prepend">
								<span className="input-group-text" id={`public-key-${shortName}`}>
									publiс API-key
								</span>
							</div>
							<input
								type="text"
								className="form-control"
								id={`publicKey-${shortName}`}
								aria-describedby={`public-key-${shortName}`}
							/>
						</div>
					</div>
					<div className="input-group mb-3">
						<div className="input-group-prepend">
							<span className="input-group-text" id={`secret-key-${shortName}`}>
								secret API-key
							</span>
						</div>
						<input
							type="password"
							className="form-control"
							id={`secretKey-${shortName}`}
							aria-describedby={`secret-key-${shortName}`}
						/>
					</div>
					<div className="form-group">
						<div className="input-group mb-3">
							<div className="input-group-prepend">
								<span className="input-group-text" id={`pass-phrase-${shortName}`}>
									passPhrase
								</span>
							</div>
							<input
								type="text"
								className="form-control"
								id={`passPhrase-${shortName}`}
								aria-describedby={`pass-phrase-${shortName}`}
							/>
						</div>
					</div>
					<div className="input-group">
						<button
							type="button"
							className="btn btn-primary"
							onClick={() => {
								if (
									$(`#publicKey-${shortName}`).val() === "" ||
									$(`#secretKey-${shortName}`).val() === ""
								) {
									// показываем предупреждение
									handlerPopupWindow(STYLES.WARNING, CONSTANTS.API_KEYS_EMPTY)
									// показываем popup
									startModalAlert()
								} else {
									const objUser = {
										exchange: exchangeName,
										fieldChangeable: "apiKeys",
										id: userProfile.id,
										apiKeys: {
											publicKey: $(`#publicKey-${shortName}`).val(),
											secretKey: $(`#secretKey-${shortName}`).val(),
											passPhrase: $(`#passPhrase-${shortName}`).val(),
											dateApiKeys: new Date().getTime(),
										},
									}
									updateUser(objUser)
									// очищаем поля ключей
									$(`#publicKey-${shortName}`).val("")
									$(`#secretKey-${shortName}`).val("")
									$(`#passPhrase-${shortName}`).val("")
								}
							}}
						>
							Save
						</button>
					</div>
				</div>
				<div className="col-6">
					<p>Status</p>
					<ul>
						<li>
							Saved keys:
							<span
								className={dateApiKeys !== 0 ? "text-success" : "text-danger"}
							>
								{dateApiKeys !== 0 ? " TRUE" : " FALSE"}
							</span>
						</li>
						<li>
							Date:
							{dateApiKeys !== 0 ? getTimeDate(dateApiKeys) : ""}
						</li>
					</ul>
				</div>
			</div>
		</div>
	)

	return (
		<div className="container">
			<div className="row mt-3">
				<ul className="nav nav-pills mb-3" id="settingTabs" role="tablist">
					{/* Profile Settings */}
					<li className="nav-item">
						<a
							className="nav-link"
							id="userSettingsProfileTab"
							data-toggle="pill"
							href="#userSettingsProfile"
							role="tab"
							aria-controls="userSettingsProfile"
							aria-selected="false"
						>
							User Settings
						</a>
					</li>

					{/* Cookie_Settings*/}
					<li className="nav-item">
						<a
							className="nav-link active"
							id="cookieSettingsTab"
							data-toggle="pill"
							href="#cookieSettings"
							role="tab"
							aria-controls="cookieSettings"
							aria-selected="true"
						>
							Cookie Settings
						</a>
					</li>

					{/* App_Settings */}
					{userProfile.status === "admin" ? (
						<li className="nav-item">
							<a
								className="nav-link"
								id="appSettingsTab"
								data-toggle="pill"
								href="#appSettings"
								role="tab"
								aria-controls="appSettings"
								aria-selected="false"
							>
								App Settings
							</a>
						</li>
					) : null}
				</ul>
			</div>

			<div className="tab-content" id="settingTabsContent">
				{/* User Settings */}
				<SettingsUser
					handlerUserProfile={handlerUserProfile}
					handlerPopupWindow={handlerPopupWindow}
					userOrderStatuses={userOrderStatuses}
					getGroupItems={getGroupItems}
					checkOrderStatuses={checkOrderStatuses}
					updateUser={updateUser}
					userProfile={userProfile}
				/>

				{/* Cookie Settings */}
				<SettingsCookie
					listNavExchanges={listNavExchanges}
					listSettingItems={listSettingItems}
				/>

				{/* Application Settings */}
				<SettingsApp
					dataConstants={dataConstants}
					scrollStyle={scrollStyle}
					handlerFilterDetails={handlerFilterDetails}
					updateItemDetails={updateItemDetails}
				/>
			</div>
		</div>
	)
}
