import {MRT_ColumnDef} from "mantine-react-table";
import {useMemo} from "react";
import {DealServiceSchema} from "../../../../client";

type Props = {
    // onChange: (service: DealServiceSchema, quantity: number) => void;
    data: DealServiceSchema[];
}

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

    return useMemo<MRT_ColumnDef<DealServiceSchema>[]>(() => [
        {
            accessorKey: "service.category",
            header: "Категория",
            accessorFn: (row) => row.service.category.name,
        },
        {
            enableGrouping: false,
            accessorKey: "service.name",
            header: "Услуга",
        },
        {
            enableGrouping: false,
            accessorKey: "price",
            header: "Цена",
        },
        {
            enableGrouping: false,
            accessorKey: "service.cost",
            header: "Себестоимость"
        },
        {
            enableGrouping: false,
            accessorKey: "quantity",
            header: "Количество",
        },
        {
            enableGrouping: false,
            header: "Сумма",
            Cell: ({row}) => {
                return row.original.quantity * row.original.price;
            },
            aggregationFn: "sum",
            AggregatedCell: ({cell}) => {
                return <>Итоговая сумма по категории: {" "}
                    {
                        cell.row.subRows?.reduce((acc, row) =>
                            acc + row.original.quantity * row.original.price, 0)
                    }
                </>;
            },
            Footer: <>Итоговая сумма по услугам: {totalPrice}</>

        }
    ], []);
}