import { ServiceCategorySchema } from "../../../client";
import { Button, Flex, rem, TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import { CreateEditFormProps } from "../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";

type Props = CreateEditFormProps<ServiceCategorySchema>;
const CreateServiceCategoryModal = ({
                                        context,
                                        id,
                                        innerProps,
                                    }: ContextModalProps<Props>) => {
    const isEditing = "onChange" in innerProps;
    const initialValues = isEditing ? innerProps.element : { name: "" };
    const form = useForm({
        initialValues,
        validate: {
            name: name =>
                name.trim() !== ""
                    ? null
                    : "Необходимо ввести название категории",
        },
    });
    const onSubmit = (values: { name: string }) => {
        if (isEditing) {
            innerProps.onChange({ ...innerProps.element, ...values });
        } else {
            innerProps.onCreate({
                ...values,
                cardServiceRank: "",
                productServiceRank: "", id: -1,
            });
        }
        context.closeContextModal(id);
    };
    const onCancelClick = () => {
        context.closeContextModal(id);
    };
    return (
        <>
            <form onSubmit={form.onSubmit(values => onSubmit(values))}>
                <Flex
                    gap={rem(10)}
                    direction={"column"}>
                    <TextInput
                        placeholder={"Введите название категори"}
                        label={"Название категории"}
                        {...form.getInputProps("name")}
                    />

                    <Flex
                        justify={"center"}
                        mt={rem(5)}
                        gap={rem(10)}>
                        <Button
                            onClick={() => onCancelClick()}
                            variant={"subtle"}>
                            Отменить
                        </Button>
                        <Button
                            type={"submit"}
                            variant={"default"}>
                            Сохранить
                        </Button>
                    </Flex>
                </Flex>
            </form>
        </>
    );
};
export default CreateServiceCategoryModal;
