import React, {ComponentProps, MutableRefObject, useEffect, useRef, useState} from 'react';
import {IntlTelInputRef} from "intl-tel-input/react";
import {Iti} from "intl-tel-input";

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

	const inputRef = useRef<HTMLInputElement>(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;
