import {ProductSchema} from "../../../../client";
import {FC} from "react";
import {BaseTable} from "../../../../components/BaseTable/BaseTable.tsx";
import {MRT_TableOptions} from "mantine-react-table";
import {useProductsTableColumns} from "./columns.tsx";
import {ActionIcon, Flex, Tooltip} from "@mantine/core";
import {IconBarcode, IconEdit, IconTrash} from "@tabler/icons-react";
import {CRUDTableProps} from "../../../../types/CRUDTable.tsx";
import {modals} from "@mantine/modals";


const ProductsTable: FC<CRUDTableProps<ProductSchema>> = ({items, onDelete, onChange, tableRef}) => {
    const columns = useProductsTableColumns();
    const onEditClick = (product: ProductSchema) => {
        if (!onChange) return;
        modals.openContextModal({
            modal: "createProduct",
            title: 'Создание товара',
            withCloseButton: false,
            innerProps: {
                onChange: (newProduct) => onChange(newProduct),
                product: product,
            }
        })
    }
    const onPrintBarcodeClick = (product: ProductSchema) => {
        modals.openContextModal({
            modal: "printBarcode",
            title: 'Печать штрихкода',
            withCloseButton: true,
            innerProps: {
                productId: product.id
            }
        })
    }
    return (
        <BaseTable
            ref={tableRef}
            data={items}
            columns={columns}
            restProps={{
                enableColumnActions: false,
                enableRowActions: true,
                renderRowActions: ({row}) => (
                    <Flex gap="md">
                        <Tooltip label="Печать штрихкода">
                            <ActionIcon
                                onClick={() => onPrintBarcodeClick(row.original)}
                                variant={"default"}>
                                <IconBarcode/>
                            </ActionIcon>
                        </Tooltip>
                        <Tooltip label="Редактировать">
                            <ActionIcon
                                onClick={() => onEditClick(row.original)}
                                variant={"default"}>
                                <IconEdit/>
                            </ActionIcon>
                        </Tooltip>
                        <Tooltip label="Удалить">
                            <ActionIcon onClick={() => {
                                if (onDelete) onDelete(row.original);
                            }} variant={"default"}>
                                <IconTrash/>
                            </ActionIcon>
                        </Tooltip>
                    </Flex>
                )
            } as MRT_TableOptions<ProductSchema>}
        />
    )
}

export default ProductsTable;