import {useMemo, useState} from 'react';
import renderHtmlAttributes from "../../utils/renderHtmlAttributes";
import useFormSubmitSuccess from "../../hooks/useFormSubmitSuccess";
import {format, useNumberFormat} from "@react-input/number-format";
import type {NumberFormatOptions} from "@react-input/number-format/types";
import UpgradeOverlay from "../../components/UpgradeOverlay";
import type {FreemiusProps} from "../../types/freemius";

type FieldProps = {
	itemId: string
	formId: string
	attrs: Record<string, string | string[]>
	value: string
	unit: string
	unitDisplay: 'short' | 'narrow' | 'long'
	signDisplay: 'auto' | 'never' | 'always' | 'exceptZero'
	groupDisplay: boolean
	locales: string
	minimumIntegerDigits: number
	maximumIntegerDigits: number | undefined
	minimumFractionDigits: number | undefined
	maximumFractionDigits: number | undefined
	placeholder: string
} & FreemiusProps

const Field = (props: FieldProps) => {

	const options: NumberFormatOptions = useMemo(() => {
		return {
			...(props.locales && {
				locales: props.locales,
			}),
			format: 'unit',
			unit: props.unit,
			unitDisplay: props.unitDisplay,
			groupDisplay: props.groupDisplay,
			signDisplay: props.signDisplay,
			minimumIntegerDigits: props.minimumIntegerDigits,
			...(props.maximumIntegerDigits && {
				maximumIntegerDigits: props.maximumIntegerDigits
			}),
			...(props.minimumFractionDigits && {
				minimumFractionDigits: props.minimumFractionDigits
			}),
			...(props.maximumFractionDigits && {
				maximumFractionDigits: props.maximumFractionDigits
			}),
		}
	}, [props.groupDisplay, props.locales, props.maximumFractionDigits, props.maximumIntegerDigits, props.minimumFractionDigits, props.minimumIntegerDigits, props.signDisplay, props.unit, props.unitDisplay]);

	const inputRef = useNumberFormat(options);

	const attrs = useMemo(() => renderHtmlAttributes(props.attrs), [props.attrs]);

	const defaultValue = useMemo(() => {
		if (props.value) {
			return format(props.value, options);
		}
		return '';
	}, [options, props.value]);

	const [value, setValue] = useState(defaultValue);

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

	return (
		<>
			{!props.freemius.can_use_premium_code && <UpgradeOverlay url={props.freemius.get_upgrade_url}/>}
			<input
				ref={inputRef}
				{...attrs}
				placeholder={props.placeholder}
				value={value}
				onChange={e => {
					if (!props.freemius.can_use_premium_code) {
						return;
					}
					setValue(e.target.value);
				}}
			/>
		</>
	);
};

export default Field;
