import React, { useEffect } from "react"; // next import { useRouter } from "next/router"; // swr import { mutate } from "swr"; // react hook form import { Controller, useForm } from "react-hook-form"; // headless import { Dialog, Transition } from "@headlessui/react"; // services import cycleService from "lib/services/cycles.service"; // fetch keys import { CYCLE_LIST } from "constants/fetch-keys"; // common import { renderDateFormat } from "constants/common"; // ui import { Button, Input, TextArea, Select, CustomSelect } from "ui"; // types import type { ICycle } from "types"; type Props = { isOpen: boolean; setIsOpen: React.Dispatch>; projectId: string; data?: ICycle; }; const defaultValues: Partial = { name: "", description: "", status: "draft", start_date: new Date().toString(), end_date: new Date().toString(), }; const CreateUpdateCycleModal: React.FC = ({ isOpen, setIsOpen, data, projectId }) => { const router = useRouter(); const { workspaceSlug } = router.query; const { register, formState: { errors, isSubmitting }, handleSubmit, control, reset, setError, } = useForm({ defaultValues, }); useEffect(() => { if (data) { setIsOpen(true); reset(data); } else { reset(defaultValues); } }, [data, setIsOpen, reset]); const onSubmit = async (formData: ICycle) => { if (!workspaceSlug) return; const payload = { ...formData, start_date: formData.start_date ? renderDateFormat(formData.start_date) : null, end_date: formData.end_date ? renderDateFormat(formData.end_date) : null, }; if (!data) { await cycleService .createCycle(workspaceSlug as string, projectId, payload) .then((res) => { mutate(CYCLE_LIST(projectId), (prevData) => [res, ...(prevData ?? [])], false); handleClose(); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof typeof defaultValues, { message: err[key].join(", "), }); }); }); } else { await cycleService .updateCycle(workspaceSlug as string, projectId, data.id, payload) .then((res) => { mutate( CYCLE_LIST(projectId), (prevData) => { const newData = prevData?.map((item) => { if (item.id === res.id) { return res; } return item; }); return newData; }, false ); handleClose(); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof typeof defaultValues, { message: err[key].join(", "), }); }); }); } }; const handleClose = () => { setIsOpen(false); reset(defaultValues); }; return (
{data ? "Update" : "Create"} Cycle