import { ContextModalProps } from "@mantine/modals";
import { FlatPlaceTypeSchema, PlaceSchema } from "../../../../../../client";
import { Button, Stack } from "@mantine/core";
import { useForm } from "@mantine/form";
import { PlaceCrud } from "../hooks/usePlacesCrud.tsx";
import PlaceTypeSelect from "../components/PlaceTypeSelect.tsx";

type Props = {
    placeCrud: PlaceCrud;
    parent?: PlaceSchema;
    placeTypes: FlatPlaceTypeSchema[];
}

type PlaceModalForm = {
    placeType: PlaceSchema | null;
}

const PlaceModal = ({
                        context,
                        id,
                        innerProps,
                    }: ContextModalProps<Props>) => {
    const { parent, placeCrud, placeTypes } = innerProps;

    const closeModal = () => {
        context.closeContextModal(id);
    };

    const initialValues: PlaceModalForm = {
        placeType: null,
    };
    const form = useForm<PlaceModalForm>({
        initialValues,
        validate: {
            placeType: placeType => !placeType && "Необходимо указать тип",
        },
    });

    const onSubmit = (values: PlaceModalForm) => {
        if (!values.placeType) return;
        placeCrud.onCreate({
            placeTypeId: values.placeType.id,
            parentId: parent?.id || null,
        });
        closeModal();
    };

    return (
        <form onSubmit={form.onSubmit(values => onSubmit(values))}>
            <Stack>
                <PlaceTypeSelect
                    label={"Тип места на складе"}
                    {...form.getInputProps("placeType")}
                    data={placeTypes}
                />

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

export default PlaceModal;
