import React, { useState } from "react";
import { View, Text, TextInput, StyleSheet, ViewStyle, StyleProp } from "react-native";

interface NumberInputProps {
	placeholder: string;
	extendedStyle?: StyleProp<ViewStyle>;
	onChangeText: (text: string) => void;
}

const NumberInput: React.FC<NumberInputProps> = ({ placeholder, extendedStyle, onChangeText }) => {
	const [inputValue, setInputValue] = useState<string>("");
	const [error, setError] = useState("");

	//if users input non-number, show error message
	const validateInput = (input: string) => {
		const regex = /^[0-9\b]+$/;
		if (!input.trim()) {
			setError("");
			setInputValue(input);

			onChangeText(input);
			return;
		}
		if (regex.test(input)) {
			setInputValue(input);
			setError("");
			onChangeText(input);
		} else {
			setError("Please enter only numbers");
		}
	};
	return (
		<View>
			<View style={[styles.inputContainer, extendedStyle]}>
				<TextInput
					keyboardType="numeric"
					placeholder={placeholder}
					style={[styles.input]}
					onChangeText={(text) => validateInput(text)}
					value={inputValue}
				/>
			</View>
			{error && <Text style={styles.errorMessage}>{error}</Text>}
		</View>
	);
};

const styles = StyleSheet.create({
	inputContainer: {
		width: "100%",
		maxWidth: "100%",
		flexDirection: "row",
		alignItems: "center",
		justifyContent: "center",
		borderWidth: 1,
		borderColor: "#bbbbbb",
		borderRadius: 10,
		padding: 15,
		margin: 10,
	},
	input: {
		flex: 1,
		marginLeft: 5,
	},
	errorMessage: {
		fontSize: 12,
		color: "#ff0033",
		marginLeft: 20,
	},
});
export default NumberInput;
