import { CardProductSchema } from "../../../client";
import { ContextModalProps } from "@mantine/modals";
import { Button, Flex, rem } from "@mantine/core";
import { useState } from "react";
import ObjectMultiSelect from "../../../components/ObjectMultiSelect/ObjectMultiSelect.tsx";
import { notifications } from "../../../shared/lib/notifications.ts";

type Props = {
    cardProducts: CardProductSchema[];
    cardProduct: CardProductSchema;
    onSelect: (
        sourceProduct: CardProductSchema,
        destinationProducts: CardProductSchema[]
    ) => void;
};

const SelectCardProductsModal = ({
    context,
    id,
    innerProps,
}: ContextModalProps<Props>) => {
    const [cardProducts, setCardProducts] = useState<CardProductSchema[]>([]);
    const onSelectClick = () => {
        if (!cardProducts) {
            notifications.error({
                message:
                    "Выберите товары на которые необходимо продублировать услуги",
            });
            return;
        }
        innerProps.onSelect(innerProps.cardProduct, cardProducts);
        context.closeContextModal(id);
    };
    const onDuplicateAllClick = () => {
        innerProps.onSelect(
            innerProps.cardProduct,
            innerProps.cardProducts.filter(
                item => item !== innerProps.cardProduct
            )
        );
        context.closeContextModal(id);
    };
    return (
        <Flex
            direction={"column"}
            gap={rem(10)}>
            <Flex>
                <ObjectMultiSelect<CardProductSchema>
                    w={"100%"}
                    label={"Товары"}
                    placeholder={
                        "Выберите товары на которые нужно продублировать услуги"
                    }
                    onChange={setCardProducts}
                    value={cardProducts}
                    data={innerProps.cardProducts}
                    getLabelFn={item => item.product.name}
                    getValueFn={item => item.product.id.toString()}
                    filterBy={item => item !== innerProps.cardProduct}
                />
            </Flex>
            <Flex
                gap={rem(10)}
                justify={"flex-end"}>
                <Button
                    variant={"subtle"}
                    onClick={() => context.closeContextModal(id)}>
                    Отменить
                </Button>
                <Button onClick={onDuplicateAllClick}>
                    Продублировать на все товары
                </Button>
                <Button
                    onClick={onSelectClick}
                    variant={"default"}>
                    Продублировать
                </Button>
            </Flex>
        </Flex>
    );
};

export default SelectCardProductsModal;
