import {BaseTable} from "../../../../components/BaseTable/BaseTable.tsx";
import useDealProductsTableColumns from "./columns.tsx";
import {FC} from "react";
import {CRUDTableProps} from "../../../../types/CRUDTable.tsx";
import {DealProductSchema, ProductService} from "../../../../client";
import {ActionIcon, Button, Flex, rem, Tooltip} from "@mantine/core";
import {MRT_TableOptions} from "mantine-react-table";
import {modals} from "@mantine/modals";
import {IconBarcode, IconEdit, IconTrash} from "@tabler/icons-react";
import {notifications} from "../../../../shared/lib/notifications.ts";
import {CreateProductRequest} from "../../../ProductsPage/types.ts";

type RestProps = {
    clientId: number;
    onMultipleDelete?: (items: DealProductSchema[]) => void;
}
type Props = CRUDTableProps<DealProductSchema> & RestProps;
const DealProductsTable: FC<Props> = (props: Props) => {
    const {items, clientId, onChange, onCreate, onDelete, onMultipleDelete} = props;

    const columns = useDealProductsTableColumns({
        onChange: (product, quantity) => {
            if (!onChange) return;
            if (quantity <= 0 && onDelete) {
                onDelete(product);
                return;
            }
            onChange({...product, quantity})
        },
        data: items

    });

    const onCreateClick = () => {
        if (!onCreate) return;
        modals.openContextModal({
            modal: "addDealProduct",
            title: "Добавление товара",
            innerProps: {
                onCreate: (product) => onCreate(product as DealProductSchema),
                clientId
            },
            size: "lg"
        })
    }
    const onPrintBarcodeClick = (product: DealProductSchema) => {
        modals.openContextModal({
            modal: "printBarcode",
            title: 'Печать штрихкода',
            withCloseButton: true,
            innerProps: {
                productId: product.product.id,
                defaultQuantity: product.quantity
            }
        })
    }
    const onCreateProduct = (newProduct: CreateProductRequest) => {
        ProductService.createProduct({
            requestBody: newProduct
        }).then(({ok, message}) => {
            notifications.guess(ok, {message: message});
        })
    }
    const onCreateProductClick = () => {
        modals.openContextModal({
            modal: "createProduct",
            title: 'Создание товара',
            withCloseButton: false,
            innerProps: {
                clientId: clientId,
                onCreate: onCreateProduct
            }
        })
    }
    const onEditClick = (product: DealProductSchema) => {
        if (!onChange) return;
        modals.openContextModal({
            modal: "addDealProduct",
            title: 'Создание товара',
            withCloseButton: false,
            innerProps: {
                clientId: clientId,
                element: product,
                onChange: onChange
            },
            size: "lg"

        })
    }
    return (
        <BaseTable
            data={items}
            columns={columns}
            restProps={{
                enableBottomToolbar: true,
                enableRowActions: true,
                enableRowSelection: true,
                renderRowActions: ({row}) => (
                    <Flex gap="md">
                        <Tooltip label="Удалить">
                            <ActionIcon onClick={() => onDelete && onDelete(row.original)} variant={"default"}>
                                <IconTrash/>
                            </ActionIcon>
                        </Tooltip>
                        <Tooltip label="Печать штрихкода">
                            <ActionIcon onClick={() => onPrintBarcodeClick(row.original)} variant={"default"}>
                                <IconBarcode/>
                            </ActionIcon>
                        </Tooltip>
                        <Tooltip label="Редактировать">
                            <ActionIcon onClick={() => onEditClick(row.original)} variant={"default"}>
                                <IconEdit/>
                            </ActionIcon>
                        </Tooltip>
                    </Flex>
                ),
                renderBottomToolbar: ({table}) => (
                    <Flex justify={"flex-end"} gap={rem(10)} p={rem(10)}>
                        {(onMultipleDelete && table.getSelectedRowModel().rows.length > 0) && (
                            <Button
                                onClick={() => {
                                    onMultipleDelete(table.getSelectedRowModel().rows.map(row => row.original))
                                }}
                                variant={"filled"}
                                color={"red"}
                            >
                                Удалить выбранные
                            </Button>
                        )}
                        <Button
                            variant={"default"}
                            onClick={onCreateProductClick}>
                            Создать товар
                        </Button>

                        <Button
                            onClick={onCreateClick}
                            variant={"default"}>
                            Добавить товар в сделку
                        </Button>
                    </Flex>
                ),
            } as MRT_TableOptions<DealProductSchema>}
        />
    )
}

export default DealProductsTable;