| 1 | import { useState, useEffect } from "react";
|
| 2 | import { View, Text, Pressable, StyleSheet } from "react-native";
|
| 3 | import DateTimePicker, {
|
| 4 | DateTimePickerEvent,
|
| 5 | } from "@react-native-community/datetimepicker";
|
| 6 | import { format } from "date-fns";
|
| 7 | import { MaterialIcons } from "@expo/vector-icons";
|
| 8 | import { Colors } from "@/constants/theme";
|
| 9 | import { Label } from "@/components/ui/Input";
|
| 10 |
|
| 11 | interface DatePickerProps {
|
| 12 | label: string;
|
| 13 | initialDate?: Date;
|
| 14 | onChange: (date: Date) => void;
|
| 15 | minimumDate?: Date;
|
| 16 | maximumDate?: Date;
|
| 17 | }
|
| 18 |
|
| 19 | export const DatePickerField: React.FC<DatePickerProps> = ({
|
| 20 | label,
|
| 21 | initialDate = new Date(),
|
| 22 | onChange,
|
| 23 | minimumDate,
|
| 24 | maximumDate,
|
| 25 | }) => {
|
| 26 | const [date, setDate] = useState(initialDate);
|
| 27 | const [show, setShow] = useState(false);
|
| 28 |
|
| 29 | useEffect(() => {
|
| 30 | setDate(initialDate);
|
| 31 | }, [initialDate]);
|
| 32 |
|
| 33 | const openPicker = () => setShow(true);
|
| 34 |
|
| 35 | const handleChange = (event: DateTimePickerEvent, selectedDate?: Date) => {
|
| 36 | setShow(false);
|
| 37 |
|
| 38 | if (selectedDate) {
|
| 39 | setDate(selectedDate);
|
| 40 | if (onChange) onChange(selectedDate);
|
| 41 | }
|
| 42 | };
|
| 43 |
|
| 44 | const formatted = format(date, "dd/MM/yyyy");
|
| 45 |
|
| 46 | return (
|
| 47 | <View>
|
| 48 | <Label text={label} />
|
| 49 |
|
| 50 | <Pressable
|
| 51 | onPress={openPicker}
|
| 52 | style={({ pressed }) => [styles.container, pressed && styles.pressed]}
|
| 53 | >
|
| 54 | <Text style={styles.dateText}>{formatted}</Text>
|
| 55 | <MaterialIcons name="calendar-month" size={22} color="#6B7280" />
|
| 56 | </Pressable>
|
| 57 |
|
| 58 | {show && (
|
| 59 | <DateTimePicker
|
| 60 | value={date}
|
| 61 | mode="date"
|
| 62 | display={"default"}
|
| 63 | onChange={handleChange}
|
| 64 | minimumDate={minimumDate}
|
| 65 | maximumDate={maximumDate}
|
| 66 | />
|
| 67 | )}
|
| 68 | </View>
|
| 69 | );
|
| 70 | };
|
| 71 |
|
| 72 | const styles = StyleSheet.create({
|
| 73 | label: {
|
| 74 | fontWeight: "500",
|
| 75 | color: Colors.light.textSecondary,
|
| 76 | fontSize: 12,
|
| 77 | marginBottom: 8,
|
| 78 | letterSpacing: 0.5,
|
| 79 | textTransform: "uppercase",
|
| 80 | },
|
| 81 | container: {
|
| 82 | flexDirection: "row",
|
| 83 | alignItems: "center",
|
| 84 | justifyContent: "space-between",
|
| 85 | backgroundColor: "#F3F4F6", // light gray pill
|
| 86 | paddingVertical: 14,
|
| 87 | paddingHorizontal: 16,
|
| 88 | borderRadius: 10,
|
| 89 | borderWidth: 0.5,
|
| 90 | borderColor: "#E5E7EB",
|
| 91 | minWidth: 220,
|
| 92 | },
|
| 93 | pressed: {
|
| 94 | opacity: 0.8,
|
| 95 | },
|
| 96 | dateText: {
|
| 97 | color: "#111827",
|
| 98 | fontSize: 16,
|
| 99 | fontWeight: "600",
|
| 100 | },
|
| 101 | });
|