import * as React from "react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import {
	faVolumeUp,
	faVolumeMute,
} from "@fortawesome/free-solid-svg-icons"
import { getColorValueStatus } from "../common"
import { ICounterOrders } from "../types"
import "../styles/OrdersPanel.css"

export const CounterOrders: React.FC<ICounterOrders> = props => {
	const {
		orders,
		isSound,
		loading,
		statuses,
		prefix,
		soundAlert,
		orderStatus,
		handlerSound,
	} = props

	// получение количества ордеров по их статусу
	const getCountTypeOrders = React.useCallback(
		(orders: any, valueStatus: string) => {
			let count = 0
			if (orders.length !== 0) {
				for (let i = 0; i < orders.length; i++) {
					if (
						orders[i] !== null &&
						orders[i].statusProps.value === valueStatus
					) {
						count++
					}
				}
			}
			return count
		},
		[]
	)

	React.useEffect(() => {
		const audio = new Audio(soundAlert)
		// let alertOrders = 0
		// if (prefix === "GX") {
		// 	alertOrders =
		// 		getCountTypeOrders(orders, "waiting") +
		// 		getCountTypeOrders(orders, "pending")
		// } else if (prefix === "BZ") {
		// 	alertOrders =
		// 		getCountTypeOrders(orders, "trade_created") +
		// 		getCountTypeOrders(orders, "confirm_trade")
		// } // все другие
		// else alertOrders = getCountTypeOrders(orders, orderStatus.toString())
		const alertOrders = getCountTypeOrders(orders, orderStatus.toString())
		if (isSound && !loading && alertOrders > 0) audio.play()
	}, [
		getCountTypeOrders,
		prefix,
		orders,
		soundAlert,
		isSound,
		loading,
		orderStatus,
	])

	const iconType = isSound ? faVolumeUp : faVolumeMute
	const colorBtn = isSound ? "success" : "danger"
	const orderCounterItems =
		orders.length === 0
			? null
			: statuses.map((item: any, index: number) => {
					const countOrders = getCountTypeOrders(orders, item.toString())
					const statusProps = getColorValueStatus(prefix, item.toString())
					const highlightClass =
						statusProps.value === "Unpaid" && countOrders > 0
							? "activeUnpaid"
							: "unactiveUnpaid"
					return (
						<span
							key={index}
							title={statusProps.value}
							className={`border-1 border-${statusProps.color} ${highlightClass} rounded-circle`}
						>
							{countOrders}
						</span>
					)
			  })

	return (
		<div className="orders-panel">
			<span className={`border-1 border- rounded-circle`}>{prefix}</span>
			{orderCounterItems}
			{prefix === "BN" && handlerSound ? (
				<span
					className={`border-1 border-${colorBtn} rounded-circle`}
					style={{ cursor: "pointer" }}
					onClick={() => handlerSound(!isSound)}
				>
					<FontAwesomeIcon className={`text-${colorBtn}`} icon={iconType} />
				</span>
			) : null}
		</div>
	)
}
