import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import { Button, Flex, NumberInput, rem } from "@mantine/core";
import { ClientDetailedSchema, ProductSchema, ResiduesService, UpdateResidualProductSchema } from "../../../../client";
import { ResidualModalForm, UpdateResidualProductData } from "../../types/ResidualProductData.tsx";
import { notifications } from "../../../../shared/lib/notifications.ts";
import ProductSelect from "../../../../components/ProductSelect/ProductSelect.tsx";


type Props = {
    updateOnSubmit: () => void;
    client: ClientDetailedSchema;
    residuesData: UpdateResidualProductData;
}

const ResidualProductModal = ({
                                  context,
                                  id,
                                  innerProps,
                              }: ContextModalProps<Props>) => {
    const initialValues: ResidualModalForm = {
        quantity: innerProps.residuesData.quantity ?? 0,
        product: innerProps.residuesData.product,
    };
    const form = useForm<ResidualModalForm>({
        initialValues,
        validate: {
            product: product => !product && "Необходимо выбрать товар",
            quantity: quantity => quantity === 0 && "Слишком мало товара",
        },
    });

    const updateResidualProduct = () => {
        const data = {
            ...form.values,
            productId: form.values.product!.id,
        } as UpdateResidualProductSchema;

        ResiduesService.updateResidualProduct({
            requestBody: { data },
            residualProductId: innerProps.residuesData.residualProductId,
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message: message });
                innerProps.updateOnSubmit();
                if (ok) context.closeContextModal(id);
            })
            .catch(err => console.log(err));
    };

    return (
        <form onSubmit={form.onSubmit(() => updateResidualProduct())}>
            <Flex
                direction={"column"}
                gap={rem(10)}
            >
                <ProductSelect
                    label={"Товар"}
                    placeholder={"Выберите товар"}
                    {...form.getInputProps("product")}
                    defaultValue={innerProps.residuesData.product as (ProductSchema & string)}
                    clientId={innerProps.client.id}
                />

                <NumberInput
                    label={"Количество"}
                    hideControls
                    {...form.getInputProps("quantity")}
                    min={0}
                />

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

export default ResidualProductModal;
