import {useEffect, useMemo, useRef, useState} from 'react';
import renderHtmlAttributes from "../../utils/renderHtmlAttributes";
import useFormSubmitSuccess from "../../hooks/useFormSubmitSuccess";
import type {FreemiusProps} from "../../types/freemius";
import UpgradeOverlay from "../../components/UpgradeOverlay";
import Rating from "react-rating";

type FieldProps = {
	itemId: string
	attrs: Record<string, string | string[]>
	stars: number
	icon: 'star' | 'heart' | 'smile' | 'custom'
	unmarkedStyle: 'solid' | 'outline'
	customIcon: string
	customUnmarkedIcon: string
	precision: number
	showValue: boolean
	quiet: boolean
} & FreemiusProps

const Field = (props: FieldProps) => {

	const inputRef = useRef<HTMLInputElement | null>(null);
	const attrs = useMemo(() => renderHtmlAttributes(props.attrs), [props.attrs]);

	const initialValue = useMemo(() => Number(attrs.value ?? 0), [attrs.value]);
	const [value, setValue] = useState(initialValue);
	const [hoverVal, setHoverVal] = useState(initialValue);

	const getHoverVal = useMemo(() => {
		const val = hoverVal ?? value;
		if (val <= 0) {
			return 0;
		} else if (val > props.stars) {
			return props.stars;
		}
		return val;
	}, [hoverVal, props.stars, value]);

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

	const emptySymbol = useMemo(() => {
		try {
			return decodeURIComponent(props.customIcon);
		} catch {
			return props.customIcon;
		}
	}, [props.customIcon]);

	const fullSymbol = useMemo(() => {
		try {
			return decodeURIComponent(props.customUnmarkedIcon);
		} catch {
			return props.customUnmarkedIcon;
		}
	}, [props.customUnmarkedIcon]);

	useEffect(() => {
		const element = inputRef.current;
		element?.dispatchEvent(new Event('change', {bubbles: true}));
	}, [value]);

	return (
		<>
			{!props.freemius.can_use_premium_code && <UpgradeOverlay url={props.freemius.get_upgrade_url}/>}
			<div className={'hulk-rating-field-wrap'}>
				{/*@ts-ignore*/}
				<Rating
					className={'hulk-rating-field'}
					initialRating={value}
					stop={props.stars}
					fractions={props.precision}
					quiet={props.quiet}
					emptySymbol={<span
						className={'hulk-empty-symbol'}
						dangerouslySetInnerHTML={{__html: emptySymbol}}
					/>}
					fullSymbol={<span
						className={'hulk-full-symbol'}
						dangerouslySetInnerHTML={{__html: fullSymbol}}
					/>}
					onChange={(rate) => {
						if (!props.freemius.can_use_premium_code) {
							return;
						}
						setValue(rate);
					}}
					onHover={rate => {
						if (!props.freemius.can_use_premium_code) {
							return;
						}
						setHoverVal(rate);
					}}
				/>
				{props.showValue && (
					<span className={'elementor-field-textual hulk-show-value'}>
						{getHoverVal}
					</span>
				)}
			</div>
			<input ref={inputRef} type="hidden" {...attrs} value={value > 0 ? value : ''}/>
		</>
	);
};

export default Field;
