import { useState } from "react";
import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, TouchableOpacity, View, Modal, Pressable, TextInput } from "react-native";
import DatePicker from "react-native-modern-datepicker";

type DateModalProps = {
	onDateChange: (date: string) => void;
	placeholder: string;
};
const DateModal: React.FC<DateModalProps> = ({ onDateChange, placeholder }) => {
	const [open, setOpen] = useState(false);
	const [date, setDate] = useState("");

	//open or close date calendar modal
	function openOrCloseModal() {
		setOpen(!open);
	}

	//turn date from yyyy/mm/dd to dd/mm/yyyy && send info back to parent component
	function handleChange(propDate: string) {
		const parts = propDate.split("/");
		const rearrangedParts = [parts[2], parts[1], parts[0].slice(-2)];
		const formattedDate = rearrangedParts.join("/");
		setDate(formattedDate);
		onDateChange(formattedDate);
	}

	return (
		<View style={styles.container}>
			<Pressable onPress={openOrCloseModal} style={[styles.inputContainer]}>
				{/* <Text style={styles.placeholder}>{date ? date : "DD/MM/YY"}</Text> */}
				<Text style={styles.placeholder}>{placeholder}</Text>
			</Pressable>
			<Modal animationType="slide" transparent={true} visible={open}>
				<View style={styles.centeredView}>
					<View style={styles.modalView}>
						<DatePicker mode="calendar" selected={date} onDateChange={handleChange} />
						<TouchableOpacity onPress={openOrCloseModal}>
							<Text style={styles.closeButton}>Close</Text>
						</TouchableOpacity>
					</View>
				</View>
			</Modal>
			<StatusBar style="auto" />
		</View>
	);
};

const styles = StyleSheet.create({
	container: {
		flex: 1,
		// alignItems: "center",
		// justifyContent: "center",
	},
	inputContainer: {
		// width: "50%",
		// height: 60,
		maxWidth: "100%",
		flexDirection: "row",
		// alignItems: "center",
		borderWidth: 1,
		borderColor: "#bbbbbb",
		borderRadius: 12,
		padding: 20,
	},
	placeholder: {
		fontSize: 16,
		color: "#888",
	},
	centeredView: {
		flex: 1,
		justifyContent: "center",
		alignItems: "center",
		marginTop: 22,
	},
	modalView: {
		margin: 20,
		backgroundColor: "white",
		borderRadius: 20,
		width: "90%",
		padding: 20,
		alignItems: "center",
		shadowColor: "#000",
		shadowOffset: {
			width: 0,
			height: 2,
		},
		shadowOpacity: 0.25,
		shadowRadius: 4,
		elevation: 5,
	},
	closeButton: { color: "#3f4f5c", padding: 20, borderWidth: 1, borderColor: "#bbbbbb", borderRadius: 15 },
});

export default DateModal;
