import { Button, Flex } from "@mantine/core";
import { modals } from "@mantine/modals";
import { addKitToDeal, ServicesKitSchema } from "@/lib/client";
import { useFulfillmentBaseContext } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/contexts/FulfillmentBaseContext";
import { ServiceType } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/types/service";

const ServicesActions = () => {
    const { dealServicesList, dealServicesCrud, deal } =
        useFulfillmentBaseContext();

    const onCreateClick = () => {
        const serviceIdsToExclude = dealServicesList.dealServices.map(
            service => service.service.id
        );
        modals.openContextModal({
            modal: "dealServiceEditorModal",
            innerProps: {
                onCreate: values =>
                    dealServicesCrud.onCreate({ ...values, dealId: deal.id }),
                serviceIdsToExclude,
                isEditing: false,
            },
            withCloseButton: false,
        });
    };

    const onServicesKitAdd = (servicesKit: ServicesKitSchema) => {
        addKitToDeal({
            body: {
                dealId: deal.id,
                kitId: servicesKit.id,
            },
        })
            .then(() => dealServicesList.refetch())
            .catch(err => console.error(err));
    };

    const onAddKitClick = () => {
        modals.openContextModal({
            modal: "servicesKitSelectModal",
            innerProps: {
                onSelect: onServicesKitAdd,
                serviceType: ServiceType.DEAL_SERVICE,
            },
            withCloseButton: false,
        });
    };

    return (
        <Flex
            gap={"sm"}
            mt={"auto"}>
            <Button
                onClick={onCreateClick}
                fullWidth
                variant={"default"}>
                Добавить услугу
            </Button>
            <Button
                onClick={onAddKitClick}
                fullWidth
                variant={"default"}>
                Добавить набор услуг
            </Button>
        </Flex>
    );
};

export default ServicesActions;
