import {Iti} from "intl-tel-input";
import {type ComponentProps, type MutableRefObject, useEffect, useRef, useState} from "react";
import type {IntlTelInputRef} from "@intl-tel-input/react/with-utils";

const FullPhoneInput = (
	{
		intlTelRef,
		custom_id,
		watchValue,
		...props
	}: ComponentProps<'input'> & {
		intlTelRef: MutableRefObject<IntlTelInputRef | null>,
		custom_id: string,
		watchValue: string,
	}
) => {

	const inputRef = useRef<HTMLInputElement | null>(null);
	const instanceRef = useRef<Iti | null>(null);
	const [fullPhone, setFullPhone] = useState('');

	// Get instance only once after mount
	useEffect(() => {
		if (intlTelRef.current) {
			instanceRef.current = intlTelRef.current.getInstance();
		}
	}, []);

	// Use the stored instance on watchValue change
	useEffect(() => {
		const instance = instanceRef.current;
		if (!instance) return;
		setFullPhone(instance.getNumber());
	}, [watchValue]);

	return (
		<input
			ref={inputRef}
			type="hidden"
			name={`form_fields[${custom_id}]`}
			defaultValue={fullPhone}
			{...props}
		/>
	);
};

export default FullPhoneInput;
