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

type FieldProps = {
	itemId: string
	formId: string
	attrs: Record<string, string | string[]>
	value: readonly { value: string; label: string }[];
	options: { value: string; label: string }[]
	isMulti: boolean
	isClearable: boolean
	isRtl: boolean
	isSearchable: boolean
	placeholder: string
	noOptionsMessage: string
	isOptionDisabled: boolean
	minimumSelectionLength: number
	maximumSelectionLength: number
	filterOption: boolean;
	ignoreCase: boolean;
	ignoreAccents: boolean;
	matchFrom: 'any' | 'start'
} & FreemiusProps

const Field = (props: FieldProps) => {

	const parentRef = useRef<HTMLDivElement>(null);
	const containerRef = useRef<any>(null);
	const attrs = useMemo(() => renderHtmlAttributes(props.attrs), [props.attrs]);

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

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

	useEffect(() => {
		const element = containerRef.current?.controlRef
			.closest('.hulk_affef_select2_wrap')
			.querySelector(`input[name="${attrs.name}"]`);
		element?.dispatchEvent(new Event('change', {bubbles: true}));
	}, [attrs.name, value]);

	const isOptionDisabled = useCallback((option: any) => {
		return (value.length >= props.maximumSelectionLength) && (props.maximumSelectionLength > 0) &&
			!value.some((s: any) => s.value === option.value);
	}, [props.maximumSelectionLength, value]);

	return (
		<div ref={parentRef} className={'hulk-select2-parent'}>
			{!props.freemius.can_use_premium_code && <UpgradeOverlay url={props.freemius.get_upgrade_url}/>}
			<Select
				ref={containerRef}
				{...attrs}
				className={'hulk-select2-container'}
				classNamePrefix={'hulk-ffef'}
				options={props.options}
				delimiter={', '}
				isClearable={props.isClearable}
				isMulti={props.isMulti}
				isRtl={props.isRtl}
				isSearchable={props.isSearchable}
				placeholder={props.placeholder}
				{...(props.filterOption && {
					filterOption: createFilter({
						ignoreCase: props.ignoreCase,
						ignoreAccents: props.ignoreAccents,
						matchFrom: props.matchFrom,
					})
				})}
				value={value}
				{...((props.isMulti && props.isOptionDisabled) && {
					isOptionDisabled,
				})}
				onChange={newValue => {
					if (!props.freemius.can_use_premium_code) {
						return;
					}
					setValue(newValue);
				}}
				{...(props.noOptionsMessage && {
					noOptionsMessage: (obj) => {
						return obj.inputValue = props.noOptionsMessage;
					}
				})}
			/>
		</div>
	);
};

export default Field;
