"use client";

import { useState } from "react";
import { Button, Flex, Text } from "@mantine/core";
import { ContextModalProps } from "@mantine/modals";
import ObjectMultiSelect from "@/components/selects/ObjectMultiSelect/ObjectMultiSelect";
import { DealProductSchema } from "@/lib/client";
import { notifications } from "@/lib/notifications";

type Props = {
    dealProducts: DealProductSchema[];
    sourceDealProduct: DealProductSchema;
    duplicateServices: (
        sourceDealProduct: DealProductSchema,
        targetDealProducts: DealProductSchema[]
    ) => void;
};

const DuplicateServicesModal = ({
    context,
    id,
    innerProps,
}: ContextModalProps<Props>) => {
    const [selectedDealProducts, setSelectedDealProducts] = useState<
        DealProductSchema[]
    >([]);

    const onDealProductSelect = () => {
        if (!selectedDealProducts) {
            notifications.error({
                message:
                    "Выберите товары на которые необходимо продублировать услуги",
            });
            return;
        }
        innerProps.duplicateServices(
            innerProps.sourceDealProduct,
            selectedDealProducts
        );
        context.closeContextModal(id);
    };

    const onDuplicateAllClick = () => {
        innerProps.duplicateServices(
            innerProps.sourceDealProduct,
            innerProps.dealProducts.filter(
                item => item !== innerProps.sourceDealProduct
            )
        );
        context.closeContextModal(id);
    };

    return (
        <Flex
            direction={"column"}
            gap={"xs"}>
            <ObjectMultiSelect
                w={"100%"}
                label={"Товары"}
                placeholder={
                    "Выберите товары на которые нужно продублировать услуги"
                }
                onChange={setSelectedDealProducts}
                value={selectedDealProducts}
                data={innerProps.dealProducts}
                getLabelFn={item => item.product.name}
                getValueFn={item => item.product.id.toString()}
                filterBy={item => item !== innerProps.sourceDealProduct}
            />
            <Flex
                gap={"xs"}
                justify={"flex-end"}>
                <Button
                    variant={"subtle"}
                    onClick={() => context.closeContextModal(id)}>
                    <Text>Отменить</Text>
                </Button>
                <Button
                    variant={"default"}
                    onClick={onDuplicateAllClick}>
                    <Text>Продублировать на все товары</Text>
                </Button>
                <Button
                    onClick={onDealProductSelect}
                    variant={"default"}>
                    <Text>Продублировать</Text>
                </Button>
            </Flex>
        </Flex>
    );
};

export default DuplicateServicesModal;
