import { useMemo } from "react";
import { DataTableColumn } from "mantine-datatable";
import { 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)}
                        />
                    ),
                },
                {
                    accessor: "service.name",
                    title: "Услуга",
                    width: "70%",
                },
                {
                    accessor: "price",
                    title: "Цена",
                    width: "30%",
                    render: productService =>
                        productService.price.toLocaleString("ru"),
                    footer: data.length > 0 && (
                        <Text fw={700}>
                            Итог: {totalPrice.toLocaleString("ru")}₽
                        </Text>
                    ),
                },
            ] as DataTableColumn<ProductServiceSchema>[],
        [totalPrice]
    );
};

export default useProductServicesTableColumns;
