import React, {useMemo, useRef, useState} from 'react';
import renderHtmlAttributes from "../../utils/renderHtmlAttributes";
import useFormSubmitSuccess from "../../hooks/useFormSubmitSuccess";
import CurrencyInput from 'react-currency-input-field';
import {__} from "@wordpress/i18n";
import {Icon} from "@wordpress/components";
import {chevronDown, chevronUp} from "@wordpress/icons";
import UpgradeOverlay from "../../components/UpgradeOverlay";
import type {FreemiusProps} from "../../types/freemius";

type FieldProps = {
	itemId: string
	formId: string
	attrs: Record<string, string | string[]>
	value: string
	allowDecimals: boolean
	disableGroupSeparators: boolean
	allowNegativeValue: boolean
	disableAbbreviations: boolean
	decimalsLimit: number
	decimalScale: number
	fixedDecimalLength: number
	maxLength: number
	step: number
	decimalSeparator: string
	groupSeparator: string
	placeholder: string
	prefix: string
	suffix: string
	intlConfig: boolean
	intlLocale: string
	intlCurrency: string
	disableArrowButtons: boolean
} & FreemiusProps

const Field = (props: FieldProps) => {

	const inputRef = useRef<HTMLInputElement>(null);
	const intervalRef = useRef<number>(undefined);
	const timoutRef = useRef<number>(undefined);
	const attrs = useMemo(() => renderHtmlAttributes(props.attrs), [props.attrs]);

	const [value, setValue] = useState(props.value);

	// Reset after form submit
	useFormSubmitSuccess(inputRef, () => {
		setValue(props.value);
	}, [props.value]);

	function dispatchIncrement() {
		const downArrowEvent = new KeyboardEvent("keydown", {
			key: "ArrowUp",
			code: "ArrowUp",
			bubbles: true
		});
		inputRef.current?.dispatchEvent(downArrowEvent);
	}

	function dispatchDecrement() {
		const downArrowEvent = new KeyboardEvent("keydown", {
			key: "ArrowDown",
			code: "ArrowDown",
			bubbles: true
		});
		inputRef.current?.dispatchEvent(downArrowEvent);
	}

	function decrement(e: any) {
		e.preventDefault();
		inputRef.current?.focus();
		dispatchDecrement();
		clearTimeout(timoutRef.current);
		timoutRef.current = setTimeout(() => {
			intervalRef.current = setInterval(dispatchDecrement, 50);
		}, 300);
	}

	function increment(e: any) {
		e.preventDefault();
		inputRef.current?.focus();
		dispatchIncrement();
		clearTimeout(timoutRef.current);
		timoutRef.current = setTimeout(() => {
			intervalRef.current = setInterval(dispatchIncrement, 50);
		}, 300);
	}

	function handleWheel(e: React.WheelEvent<HTMLInputElement>) {
		if (e.deltaY < 0) {
			// Scrolling up
			dispatchIncrement();
		} else if (e.deltaY > 0) {
			// Scrolling down
			dispatchDecrement();
		}
	}

	function handleClear() {
		clearInterval(timoutRef.current);
		clearInterval(intervalRef.current);
	}

	return (
		<>
			{!props.freemius.can_use_premium_code && <UpgradeOverlay url={props.freemius.get_upgrade_url}/>}
			<CurrencyInput
				ref={inputRef}
				{...attrs}
				allowDecimals={props.allowDecimals}
				disableGroupSeparators={props.disableGroupSeparators}
				allowNegativeValue={props.allowNegativeValue}
				disableAbbreviations={props.disableAbbreviations}
				decimalsLimit={props.decimalsLimit}
				decimalScale={props.decimalScale}
				fixedDecimalLength={props.fixedDecimalLength}
				maxLength={props.maxLength}
				step={props.step}
				decimalSeparator={props.decimalSeparator}
				groupSeparator={props.groupSeparator}
				placeholder={props.placeholder}
				prefix={props.prefix}
				suffix={props.suffix}
				{...((props.intlConfig && props.intlLocale && props.intlCurrency) && {
					intlConfig: {locale: props.intlLocale, currency: props.intlCurrency}
				})}
				value={value}
				onValueChange={(val) => {
					if (!props.freemius.can_use_premium_code) {
						return;
					}
					setValue(val ?? '');
				}}
				onWheel={handleWheel}
			/>
			{(props.step && !props.disableArrowButtons) && (
				<>
					<span
						onMouseDown={decrement}
						onMouseUp={handleClear}
						onMouseLeave={handleClear}
						tabIndex={0}
						role={'button'}
						className="hulk-spin-down"
						title={__('Decrement value', 'advanced-fields-for-elementor-forms')}
					>
						<Icon icon={chevronDown}/>
					</span>
					<span
						onMouseDown={increment}
						onMouseUp={handleClear}
						onMouseLeave={handleClear}
						tabIndex={0}
						role={'button'}
						className="hulk-spin-up"
						title={__('Increment value', 'advanced-fields-for-elementor-forms')}
					>
						<Icon icon={chevronUp}/>
					</span>
				</>
			)}
		</>
	);
};

export default Field;
