"use client";

import { NumberInput, Textarea } from "@mantine/core";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import {
    CreateDealProductSchema,
    DealProductSchema,
    UpdateDealProductSchema,
} from "@/lib/client";
import BaseFormModal, {
    CreateEditFormProps,
} from "@/modals/base/BaseFormModal/BaseFormModal";
import ProductSelect
    from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/components/ProductSelect/ProductSelect";

type RestProps = {
    clientId: number;
    productIdsToExclude?: number[];
};

type Props = CreateEditFormProps<
    CreateDealProductSchema,
    UpdateDealProductSchema,
    DealProductSchema
> &
    RestProps;

const DealProductEditorModal = ({
    context,
    id,
    innerProps,
}: ContextModalProps<Props>) => {
    const form = useForm<Partial<DealProductSchema>>({
        initialValues: innerProps.isEditing
            ? innerProps.entity
            : {
                  quantity: 1,
                  comment: "",
              },
        validate: {
            product: product => !product && "Необходимо выбрать товар",
            quantity: quantity =>
                (!quantity || quantity === 0) &&
                "Количество должно быть больше 0",
        },
    });

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

    return (
        <BaseFormModal
            {...innerProps}
            form={form}
            closeOnSubmit
            onClose={onClose}>
            <ProductSelect
                placeholder={"Выберите товар"}
                label={"Товар"}
                clientId={innerProps.clientId}
                disabled={innerProps.isEditing}
                filterBy={item =>
                    !(innerProps.productIdsToExclude || []).includes(item.id)
                }
                {...form.getInputProps("product")}
                onChange={product => {
                    form.setFieldValue("product", product);
                    form.setFieldValue("productId", product.id);
                }}
            />
            <NumberInput
                placeholder={"Введите количество"}
                label={"Количество"}
                min={1}
                {...form.getInputProps("quantity")}
            />
            <Textarea
                placeholder={"Введите комментарий"}
                label={"Комментарий"}
                {...form.getInputProps("comment")}
            />
        </BaseFormModal>
    );
};

export default DealProductEditorModal;
