"use client";

import { NumberInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import {
    CreateDealServiceSchema,
    DealServiceSchema,
    UpdateDealServiceSchema,
} from "@/lib/client";
import BaseFormModal, {
    CreateEditFormProps,
} from "@/modals/base/BaseFormModal/BaseFormModal";
import { ServiceType } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/types/service";
import ServiceWithPriceInput from "./components/ServiceWithPriceInput";

type RestProps = {
    serviceIdsToExclude?: number[];
};

type Props = CreateEditFormProps<
    CreateDealServiceSchema,
    UpdateDealServiceSchema,
    DealServiceSchema
> &
    RestProps;

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

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

    return (
        <BaseFormModal
            {...innerProps}
            form={form}
            closeOnSubmit
            onClose={onClose}>
            <ServiceWithPriceInput
                serviceProps={{
                    ...form.getInputProps("service"),
                    onChange: service => {
                        form.setFieldValue("service", service);
                        form.setFieldValue("serviceId", service.id);
                    },
                    label: "Услуга",
                    placeholder: "Выберите услугу",
                    disabled: innerProps.isEditing,
                    filterBy: item =>
                        !innerProps.serviceIdsToExclude?.includes(item.id) ||
                        innerProps.isEditing,
                }}
                priceProps={{
                    ...form.getInputProps("price"),
                    label: "Цена",
                    placeholder: "Введите цену",
                }}
                quantity={form.values.quantity || 1}
                filterType={ServiceType.DEAL_SERVICE}
                lockOnEdit={innerProps.isEditing}
            />
            <NumberInput
                placeholder={"Введите количество"}
                label={"Количество"}
                min={1}
                {...form.getInputProps("quantity")}
            />
        </BaseFormModal>
    );
};

export default DealServiceEditorModal;
