import styles from './BarcodePage.module.css';
import PageBlock from "../../components/PageBlock/PageBlock.tsx";
import {Button} from "@mantine/core";
import BarcodeTemplatesTable from "./components/BarcodeTemplatesTable/BarcodeTemplatesTable.tsx";
import useGetAllBarcodeTemplates from "../../api/barcode/useGetAllBarcodeTemplates.tsx";
import {modals} from "@mantine/modals";
import {BarcodeService, BarcodeTemplateSchema} from "../../client";
import {notifications} from "../../shared/lib/notifications.ts";

const BarcodePage = () => {
    const {barcodeTemplates, refetch} = useGetAllBarcodeTemplates();

    const onCreate = (template: BarcodeTemplateSchema) => {
        BarcodeService.createBarcodeTemplate(({
            requestBody: {
                ...template,
                attributeIds: template.attributes.map(attr => attr.id)
            }
        })).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await refetch()
        })
    }

    const onChange = (template: BarcodeTemplateSchema) => {
        BarcodeService.updateBarcodeTemplate({
            requestBody: {
                ...template,
                attributeIds: template.attributes.map(attr => attr.id)
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await refetch()
        })
    }

    const onDelete = (template: BarcodeTemplateSchema) => {
        BarcodeService.deleteBarcodeTemplate({
            requestBody: {
                id: template.id
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await refetch()
        })
    }

    const onCreateClick = () => {
        modals.openContextModal({
            modal: "barcodeTemplateFormModal",
            title: 'Создание шаблона',
            withCloseButton: false,
            innerProps: {
                onCreate: onCreate
            }
        });
    }

    return (
        <div className={styles['container']}>
            <PageBlock>
                <div className={styles['top-panel']}>
                    <Button
                        onClick={() => onCreateClick()}
                        variant={"default"}
                    >
                        Создать шаблон
                    </Button>
                </div>

            </PageBlock>
            <PageBlock>
                <BarcodeTemplatesTable
                    items={barcodeTemplates}
                    onChange={onChange}
                    onDelete={onDelete}
                />
            </PageBlock>
        </div>
    )
}

export default BarcodePage;