import { FC, useMemo } from "react";
import { Title, TitleProps } from "@mantine/core";
import { DealProductSchema } from "@/lib/client";
import { useFulfillmentBaseContext } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/contexts/FulfillmentBaseContext";

type Props = TitleProps;

const DealProductsTotalLabel: FC<Props> = ({ order = 4, ...props }) => {
    const { dealProductsList } = useFulfillmentBaseContext();

    const getProductTotal = (dealProduct: DealProductSchema) =>
        dealProduct.productServices.reduce(
            (acc, service) => acc + dealProduct.quantity * service.price,
            0
        );

    const total = useMemo(
        () =>
            dealProductsList.dealProducts.reduce(
                (acc, product) => acc + getProductTotal(product),
                0
            ),
        [dealProductsList.dealProducts]
    );

    return (
        <Title
            order={order}
            {...props}>
            Итог: {total.toLocaleString("ru")}₽
        </Title>
    );
};

export default DealProductsTotalLabel;
