import React, { useEffect } from "react"; import { mutate } from "swr"; // react-hook-form import { useForm, Controller } from "react-hook-form"; // react-color import { TwitterPicker } from "react-color"; // headless ui import { Popover, Transition } from "@headlessui/react"; // services import stateService from "services/state.service"; // hooks import useToast from "hooks/use-toast"; // ui import { Button, CustomSelect, Input, Select } from "components/ui"; // types import type { IState } from "types"; // fetch-keys import { STATE_LIST } from "constants/fetch-keys"; // constants import { GROUP_CHOICES } from "constants/"; type Props = { workspaceSlug?: string; projectId?: string; data: IState | null; onClose: () => void; selectedGroup: StateGroup | null; }; export type StateGroup = "backlog" | "unstarted" | "started" | "completed" | "cancelled" | null; const defaultValues: Partial = { name: "", color: "#000000", group: "backlog", }; export const CreateUpdateStateInline: React.FC = ({ workspaceSlug, projectId, data, onClose, selectedGroup, }) => { const { setToastAlert } = useToast(); const { register, handleSubmit, formState: { errors, isSubmitting }, setError, watch, reset, control, } = useForm({ defaultValues, }); useEffect(() => { if (data === null) return; reset(data); }, [data, reset]); useEffect(() => { if (!data) reset({ ...defaultValues, group: selectedGroup ?? "backlog", }); }, [selectedGroup, data, reset]); const handleClose = () => { onClose(); reset({ name: "", color: "#000000", group: "backlog" }); }; const onSubmit = async (formData: IState) => { if (!workspaceSlug || !projectId || isSubmitting) return; const payload: IState = { ...formData, }; if (!data) { await stateService .createState(workspaceSlug, projectId, { ...payload }) .then((res) => { mutate(STATE_LIST(projectId), (prevData) => [...(prevData ?? []), res]); handleClose(); setToastAlert({ title: "Success", type: "success", message: "State created successfully", }); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof IState, { message: err[key].join(", "), }); }); }); } else { await stateService .updateState(workspaceSlug, projectId, data.id, { ...payload, }) .then((res) => { mutate(STATE_LIST(projectId)); handleClose(); setToastAlert({ title: "Success", type: "success", message: "State updated successfully", }); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof IState, { message: err[key].join(", "), }); }); }); } }; return (
{({ open }) => ( <> {watch("color") && watch("color") !== "" && ( )} ( onChange(value.hex)} /> )} /> )}
{data && ( ( k === value.toString()) ? GROUP_CHOICES[value.toString() as keyof typeof GROUP_CHOICES] : "Select group" } input > {Object.keys(GROUP_CHOICES).map((key) => ( {GROUP_CHOICES[key as keyof typeof GROUP_CHOICES]} ))} )} /> )} ); };