import React, { useEffect } from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; // react-hook-form import { useForm } from "react-hook-form"; // services import estimatesService from "services/estimates.service"; // ui import { Input, PrimaryButton, SecondaryButton, TextArea } from "components/ui"; import { Dialog, Transition } from "@headlessui/react"; // hooks import useToast from "hooks/use-toast"; // types import { IEstimate } from "types"; // fetch-keys import { ESTIMATES_LIST } from "constants/fetch-keys"; type Props = { isOpen: boolean; handleClose: () => void; data?: IEstimate; }; const defaultValues: Partial = { name: "", description: "", }; export const CreateUpdateEstimateModal: React.FC = ({ handleClose, data, isOpen }) => { const { register, formState: { errors, isSubmitting }, handleSubmit, reset, } = useForm({ defaultValues, }); const onClose = () => { handleClose(); reset(); }; const router = useRouter(); const { workspaceSlug, projectId } = router.query; const { setToastAlert } = useToast(); const createEstimate = async (formData: IEstimate) => { if (!workspaceSlug || !projectId) return; const payload = { name: formData.name, description: formData.description, }; await estimatesService .createEstimate(workspaceSlug as string, projectId as string, payload) .then((res) => { mutate( ESTIMATES_LIST(projectId as string), (prevData) => [res, ...(prevData ?? [])], false ); }) .catch(() => { setToastAlert({ type: "error", title: "Error!", message: "Error: Estimate could not be created", }); }); onClose(); }; const updateEstimate = async (formData: IEstimate) => { if (!workspaceSlug || !projectId || !data) return; const payload = { name: formData.name, description: formData.description, }; mutate( ESTIMATES_LIST(projectId as string), (prevData) => prevData?.map((p) => { if (p.id === data.id) return { ...p, ...payload }; return p; }), false ); await estimatesService .patchEstimate(workspaceSlug as string, projectId as string, data?.id as string, payload) .then(() => handleClose()) .catch(() => { setToastAlert({ type: "error", title: "Error!", message: "Error: Estimate could not be updated", }); }); onClose(); }; useEffect(() => { reset({ ...defaultValues, ...data, }); }, [data, reset]); return ( <>
{data ? "Update" : "Create"} Estimate