import { useMemo } from "react";
import { DataTableColumn } from "mantine-datatable";
import { Box, Text } from "@mantine/core";
import UpdateDeleteTableActions from "@/components/ui/BaseTable/components/UpdateDeleteTableActions";
import { ProductServiceSchema } from "@/lib/client";

type Props = {
    data: ProductServiceSchema[];
    quantity: number;
    onChange: (dealProductService: ProductServiceSchema) => void;
    onDelete: (dealProductService: ProductServiceSchema) => void;
};

const useProductServicesTableColumns = ({
    data,
    quantity,
    onChange,
    onDelete,
}: Props) => {
    const totalPrice = useMemo(
        () => data.reduce((acc, row) => acc + row.price * quantity, 0),
        [data, quantity]
    );

    return useMemo(
        () =>
            [
                {
                    accessor: "actions",
                    title: "Действия",
                    textAlign: "center",
                    width: "0%",
                    render: dealProductService => (
                        <UpdateDeleteTableActions
                            onDelete={() => onDelete(dealProductService)}
                            onChange={() => onChange(dealProductService)}
                            style={{ padding: "var(--mantine-spacing-xs)" }}
                        />
                    ),
                },
                {
                    accessor: "service.name",
                    title: "Услуга",
                },
                {
                    accessor: "price",
                    title: "Цена",
                    render: productService =>
                        productService.price.toLocaleString("ru"),
                    footer: data.length > 0 && (
                        <Box my={"sm"}>
                            <Text fw={700}>
                                Итог: {totalPrice.toLocaleString("ru")}₽
                            </Text>
                        </Box>
                    ),
                },
            ] as DataTableColumn<ProductServiceSchema>[],
        [totalPrice]
    );
};

export default useProductServicesTableColumns;
