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;
	editable?: boolean;
}

const NumberInput: React.FC<NumberInputProps> = ({ placeholder, extendedStyle, onChangeText, editable }) => {
	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 style={[styles.mainContainer, extendedStyle]}>
			<View style={styles.inputContainer}>
				<TextInput
					keyboardType="numeric"
					placeholder={placeholder}
					placeholderTextColor={"#888888"}
					style={[styles.input]}
					onChangeText={(text) => validateInput(text)}
					value={inputValue}
					editable={editable}
				/>
			</View>
			{error && <Text style={styles.errorMessage}>{error}</Text>}
		</View>
	);
};

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