import {lazy, Suspense} from 'react';
import UpgradeOverlay from "../../components/UpgradeOverlay";
import type {FreemiusProps} from "../../types/freemius";
import type {AllOptions} from "intl-tel-input";

const TelInput = lazy(() => import("./TelInput"));

export type FieldProps = {
	id: string
	itemId: string
	formId: string
	attrs: Record<string, string | string[]>
	value: string
	initialCountry: AllOptions['initialCountry']
	autoCountry: boolean
	showFlags: boolean
	separateDialCode: boolean
	nationalMode: boolean
	strictMode: boolean
	onlyCountries: AllOptions['onlyCountries']
	excludeCountries: AllOptions['excludeCountries']
	countryOrder: AllOptions['countryOrder']
	placeholder: string
	custom_id: string
	fullPhone: boolean
	internationalisation: string
	enableValidation: boolean
	name: string
	class: string
	required: boolean
	formElement: HTMLFormElement
	_id: string
	customMessages: boolean
	TOO_SHORT: string
	TOO_LONG: string
	INVALID_BUT_POSSIBLE: string
	INVALID_COUNTRY_CODE: string
	INVALID_LENGTH: string
	NOT_A_NUMBER: string
	UNKNOWN: string
} & FreemiusProps

const defaultProps = {
	autoCountry: false,
	showFlags: true,
	separateDialCode: false,
	fullPhone: false,
	internationalisation: 'en',
	customMessages: false,
	TOO_SHORT: '',
	TOO_LONG: '',
	INVALID_BUT_POSSIBLE: '',
	INVALID_COUNTRY_CODE: '',
	INVALID_LENGTH: '',
	NOT_A_NUMBER: '',
	UNKNOWN: '',
};

const Field = (props: FieldProps) => {

	const Fallback = (
		<input
			id={`${props.id}-telephone`}
			name={props.name}
			className={props.class}
			defaultValue={props.value}
			placeholder={props.placeholder}
		/>
	)

	return (
		<>
			{!props.freemius.can_use_premium_code ? (
				<>
					<UpgradeOverlay url={props.freemius.get_upgrade_url}/>
					{Fallback}
				</>
			) : (
				<Suspense fallback={Fallback}>
					<TelInput
						{...defaultProps}
						{...props}
					/>
				</Suspense>
			)}
		</>
	);
};

export default Field;
