school-dashboard-exercise/src/Layout/Dashboard/DeleteModels.tsx
2024-06-23 12:16:01 +03:00

113 lines
2.9 KiB
TypeScript

import React, { useEffect, useState } from "react";
import { Input, Modal, Spin } from "antd";
import { useModalState } from "../../zustand/Modal";
import { ModalEnum } from "../../enums/Model";
import { useObjectToEdit } from "../../zustand/ObjectToEditState";
import { useTranslation } from "react-i18next";
interface ModalFormProps {
modalType: ModalEnum;
objectType: string;
deleteMutation: any;
objectValue: string;
}
const DeleteModels: React.FC<ModalFormProps> = ({
modalType,
objectType,
deleteMutation,
objectValue,
}) => {
const { isOpen, setIsOpen } = useModalState((state) => state);
const [inputValue, setInputValue] = useState("");
const { mutate, isLoading, isSuccess } = deleteMutation;
const { object_to_edit, set_object_to_edit } = useObjectToEdit();
useEffect(() => {
if (isSuccess) {
setIsOpen("");
setInputValue("");
}
}, [isSuccess, setIsOpen]);
const handleSubmit = () => {
mutate({
id: Number(object_to_edit?.id),
});
};
const handleCancel = () => {
setInputValue("");
setIsOpen("");
set_object_to_edit({});
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};
const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && object_to_edit?.[objectValue] === inputValue) {
handleSubmit();
}
};
const [t] = useTranslation();
return (
<Modal
className="ModalForm"
centered
width={"40vw"}
footer={null}
open={isOpen === modalType}
onCancel={handleCancel}
>
<header>
{t("practical.delete")} {t(`models.${objectType}`)}
</header>
<main className="main_modal">
<div className="ValidationField w-100 mb-5">
<label className="text ">
{t("practical.to_confirm_deletion_please_re_enter")}{" "}
{t(`input.${objectValue}`)} ({object_to_edit?.[objectValue]})
</label>
<Input
size="large"
type="text"
placeholder={`${t("practical.enter")} ${t(`input.${objectValue}`)} `}
value={inputValue}
onChange={handleChange}
onKeyDown={handleKeyPress}
/>
</div>
<div className="buttons">
<div onClick={handleCancel}>{t("practical.cancel")}</div>
<button
className={
object_to_edit?.[objectValue] !== inputValue
? "disabled_button"
: ""
}
disabled={object_to_edit?.[objectValue] !== inputValue || isLoading}
onClick={handleSubmit}
type="button"
>
{t("practical.delete")}
{isLoading && (
<span className="Spinier_Div">
<Spin />
</span>
)}
</button>
</div>
</main>
</Modal>
);
};
export default DeleteModels;