import React, { useContext, useRef, useState } from "react"; import { useRouter } from "next/router"; import { Button, FormControl, FormErrorMessage, FormLabel, Heading, HStack, Input, Popover, PopoverBody, PopoverCloseButton, PopoverContent, PopoverHeader, PopoverTrigger, VStack } from "@chakra-ui/react"; import { Formik, // FormikHelpers, FormikProps, Form, Field, FieldProps } from "formik"; import FormValidateEmoji from "./FormValidateEmoji"; import { CalenderContext } from "../../contexts/CalenderContext"; const DatePicker = (): JSX.Element => { const { title } = useContext(CalenderContext); const router = useRouter(); const [valid, setValid] = useState(false); const validateDate = ( dateString?: string | undefined ): string | undefined => { let dateError; if (dateString) { const dateArr = dateString.split("-"); if (dateArr.length !== 3) { dateError = "Please select a date."; setValid(false); } else if (dateArr.length === 3) { const date: UpdateCalendarProps = { year: parseInt(dateArr[0]), month: parseInt(dateArr[1]), day: parseInt(dateArr[2]) }; if (!/^(19|20)\d{2}$/.test(`${date.year}`)) { dateError = "Please use a year between 1900 and 2099"; setValid(false); } if (date.month < 1 || date.month > 12) { dateError = "Please use a month between 1 and 12"; setValid(false); } if (date.day < 1 || date.day > 31) { dateError = "Please use a day between 1 and 31"; setValid(false); } setValid(true); } else { setValid(true); } } else if (dateString.length === 0) { dateError = "Please select a date."; setValid(false); } else { setValid(true); } return dateError; }; const handleSubmit = (formInput?: { date?: string }): Promise => { return new Promise((resolve, reject) => { if (formInput.date) { if (!validateDate(formInput.date)) { const dateArr = formInput.date.split("-"); const date: UpdateCalendarProps = { year: parseInt(dateArr[0]), month: parseInt(dateArr[1]), day: parseInt(dateArr[2]) }; return resolve(router.push(`/calendar/${date.year}/${date.month}`)); } else { return reject("Error validating date."); } } else { return reject("Date not provided."); } }); }; // Field theme const fieldTheme = { width: "auto", bg: "gray.900", borderColor: "white", _placeholder: { color: "white" }, _focus: { bg: "#000", color: "#FFF", borderColor: "#63b3ed", boxShadow: "0 0 0 1px #63b3ed", zIndex: "1" } }; const initRef = useRef(); return ( {"Choose a Date"} { handleSubmit(data) .then(() => { actions.setSubmitting(false); actions.resetForm({ values: { date: "" } }); }) .catch(() => { actions.setSubmitting(false); }); }} > {( formProps: FormikProps<{ date: string; }> ) => (
Required fields indicated with{" "} {({ field, form }: FieldProps) => ( {"Date:"} {!form.touched.date && ( )} {form.errors.name && form.touched.date && ( )} {!form.errors.name && form.touched.date && ( )} {form.errors.date} )}
)}
); }; export default DatePicker;