import {useMemo} from "react";
import {MRT_ColumnDef} from "mantine-react-table";
import {DealProductSchema} from "../../../../client";
import {List} from "@mantine/core";

type Props = {
    onChange: (product: DealProductSchema, quantity: number) => void;
    data: DealProductSchema[];
}
const useDealProductsTableColumns = (props: Props) => {
    const {onChange, data} = props;
    const totalQuantity = useMemo(() => data.reduce((acc, row) => acc + row.quantity, 0), [data]);
    const totalPrice = useMemo(() => data.reduce((totalAcc, row) => totalAcc + row.services.reduce((singleAcc, service) => singleAcc + service.price * row.quantity, 0), 0), [data]);
    return useMemo<MRT_ColumnDef<DealProductSchema>[]>(() => [
        {
            accessorKey: "product.article",
            header: "Артикул",
            enableSorting: false,
            enableColumnActions: false,
        },
        {
            accessorKey: "product.name",
            header: "Название",
            enableSorting: false,
            enableColumnActions: false,
        },
        {
            accessorKey: "product.barcodes",
            header: "Штрихкоды",
            Cell: ({cell}) => {
                return (
                    <List size={"sm"}>

                        {cell.getValue<string[]>()?.map(barcode => (
                            <List.Item key={barcode}>
                                {barcode}
                            </List.Item>
                        ))}

                    </List>
                )
            },
            enableSorting: false,
            enableColumnActions: false,
        },
        {
            accessorKey: "quantity",
            header: "Количество",
            enableSorting: false,
            enableColumnActions: false,
            Footer: <>Всего товаров: {totalQuantity} </>,
        },
        {
            header: "Услуги",
            Cell: ({row}) => <List size={"sm"}>{
                row.original.services.map(service => `${service.service.name} (${service.price}₽ за шт)`)
                    .map(serviceText => <List.Item key={serviceText}>
                            {serviceText}
                        </List.Item>
                    )}
            </List>,
            enableColumnActions: false,
        },
        {
            header: "Итоговая стоимость услуг",
            Cell: ({row}) => <>
                {row.original.services.reduce((acc, service) => acc + row.original.quantity * service.price, 0)}</>,
            enableColumnActions: false,
            Footer: <>Всего стоимость услуг: {totalPrice}</>
        }
    ], [onChange, data])
}

export default useDealProductsTableColumns;