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

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

export const useDealServicesTableColumns = (props: Props) => {
    const {onChange, data} = props;
    const totalPrice = useMemo(() =>
            data.reduce((acc, row) => acc + row.quantity * row.service.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: "service.price",
            header: "Цена",
        },
        {
            enableGrouping: false,
            accessorKey: "quantity",
            header: "Количество",
            Cell: ({row}) => {
                return (
                    <PlusMinusInput
                        value={row.original.quantity}
                        onChange={(value) => onChange(row.original, value)}
                    />
                )
            }
        },
        {
            enableGrouping: false,
            header: "Сумма",
            Cell: ({row}) => {
                return row.original.quantity * row.original.service.price;
            },
            aggregationFn: "sum",
            AggregatedCell: ({cell}) => {
                return <>Итоговая сумма по категории: {" "}
                    {
                        cell.row.subRows?.reduce((acc, row) =>
                            acc + row.original.quantity * row.original.service.price, 0)
                    }
                </>;
            },
            Footer: <>Итоговая сумма по услугам: {totalPrice}</>

        }
    ], [onChange]);
}