import { useEffect, useState } from "react"; import { useRouter } from "next/router"; // react-hook-form import { Controller, useForm } from "react-hook-form"; // services import cyclesService from "services/cycles.service"; // hooks import useToast from "hooks/use-toast"; // ui import { DateSelect, Input, PrimaryButton, SecondaryButton, TextArea } from "components/ui"; // helpers import { getDateRangeStatus, isDateGreaterThanToday, isDateRangeValid, } from "helpers/date-time.helper"; // types import { ICycle } from "types"; type Props = { handleFormSubmit: (values: Partial) => Promise; handleClose: () => void; status: boolean; data?: ICycle; }; const defaultValues: Partial = { name: "", description: "", start_date: null, end_date: null, }; export const CycleForm: React.FC = ({ handleFormSubmit, handleClose, status, data }) => { const router = useRouter(); const { workspaceSlug, projectId } = router.query; const { setToastAlert } = useToast(); const [isDateValid, setIsDateValid] = useState(true); const { register, formState: { errors, isSubmitting }, handleSubmit, control, watch, reset, } = useForm({ defaultValues, }); const handleCreateUpdateCycle = async (formData: Partial) => { await handleFormSubmit(formData); reset({ ...defaultValues, }); }; const cycleStatus = data?.start_date && data?.end_date ? getDateRangeStatus(data?.start_date, data?.end_date) : ""; const dateChecker = async (payload: any) => { if (isDateGreaterThanToday(payload.end_date)) { await cyclesService .cycleDateCheck(workspaceSlug as string, projectId as string, payload) .then((res) => { if (res.status) { setIsDateValid(true); } else { setIsDateValid(false); setToastAlert({ type: "error", title: "Error!", message: "You have a cycle already on the given dates, if you want to create your draft cycle you can do that by removing dates", }); } }) .catch((err) => { console.log(err); }); } else { setIsDateValid(false); setToastAlert({ type: "error", title: "Error!", message: "Unable to create cycle in past date. Please enter a valid date.", }); } }; const checkEmptyDate = (watch("start_date") === "" && watch("end_date") === "") || (!watch("start_date") && !watch("end_date")); useEffect(() => { reset({ ...defaultValues, ...data, }); }, [data, reset]); return (

{status ? "Update" : "Create"} Cycle