import { DepartmentCrud } from "../hooks/useDepartmentCrud.tsx";
import { DepartmentSchema } from "../../../../../client";
import { DepartmentModalForm } from "../types/DepartmentModalForm.tsx";
import { useForm } from "@mantine/form";
import { Button, Flex, rem, TextInput } from "@mantine/core";


type Props = {
    departmentsCrud: DepartmentCrud;
    department?: DepartmentSchema;
    closeModal: () => void;
}

const DepartmentForm = ({
                            departmentsCrud,
                            department,
                            closeModal,
                        }: Props) => {
    const initialValues: Partial<DepartmentModalForm> = {
        name: department?.name ?? "",
    };
    const form = useForm<Partial<DepartmentModalForm>>({
        initialValues,
        validate: {
            name: name => !name && "Необходимо указать название",
        },
    });

    const isChanged = (): boolean => {
        return initialValues.name !== form.values.name;
    };

    const onSubmit = () => {
        if (department) {
            if (isChanged()) {
                departmentsCrud.onChange({ name: form.values.name ?? "", id: department?.id });
            }
        } else {
            departmentsCrud.onCreate({ name: form.values.name ?? "" });
        }
        closeModal();
    };

    return (
        <form onSubmit={form.onSubmit(() => onSubmit())}>
            <Flex
                direction={"column"}
                gap={rem(10)}
            >
                <TextInput
                    label={"Название"}
                    {...form.getInputProps("name")}
                />

                <Button
                    variant={"default"}
                    type={"submit"}
                >
                    Сохранить
                </Button>
            </Flex>
        </form>
    );
};

export default DepartmentForm;
