import { Accordion, ActionIcon, Box, Button, Center, Flex, Group } from "@mantine/core";
import { IconBarcode, IconPlayerPause, IconPlus, IconSpace, IconTrash } from "@tabler/icons-react";
import { ReceiptBox, ReceiptPallet } from "../types/types.tsx";
import { useReceiptContext } from "../contexts/ReceiptContext.tsx";
import AccordionBoxes from "./AccordionBoxes.tsx";
import ReceiptProducts from "./ReceiptProducts.tsx";

const AccordionPallets = () => {
    const {
        pallets,
        palletsHandlers,
        nextId,
        onObjectEditClick,
        setPalletData,
        scanningData,
        toggleScanning,
    } = useReceiptContext();

    const { palletId, boxId, isScanning } = scanningData;

    const deletePallet = (palletId: number) => {
        palletsHandlers.filter(item => item.id !== palletId);
    };

    const createBox = (pallet: ReceiptPallet) => {
        const box = {
            id: nextId(),
            residualProducts: [],
        } as ReceiptBox;

        const palletIdx = pallets.findIndex(p => p.id === pallet.id);
        palletsHandlers.setItemProp(palletIdx, "boxes", [box, ...pallets[palletIdx].boxes]);
    };

    const palletActions = (pallet: ReceiptPallet) => {
        const isScanModeVisible = pallet.boxes.length === 0;
        const isCreateButtonVisible = pallet.boxes.length > 0 || pallet.residualProducts.length > 0;
        return (
            <>
                {isScanModeVisible && (
                    <ActionIcon
                        variant={"default"}
                        onClick={() => toggleScanning(undefined, pallet.id)}
                        mr={"sm"}
                        disabled={isScanning && (pallet.id !== palletId || !!boxId)}
                    >
                        {isScanning && pallet.id === palletId && !boxId ? (
                            <IconPlayerPause />
                        ) : (
                            <IconBarcode />
                        )}
                    </ActionIcon>
                )}
                {isCreateButtonVisible && (
                    <ActionIcon
                        variant={"default"}
                        onClick={() => {
                            if (pallet.residualProducts.length > 0) {
                                onObjectEditClick(pallet, false);
                            } else {
                                createBox(pallet);
                            }
                        }}
                        disabled={isScanning}
                        mr={"sm"}
                    >
                        <IconPlus />
                    </ActionIcon>
                )}
                <ActionIcon
                    variant={"default"}
                    onClick={() => deletePallet(pallet.id)}
                    disabled={isScanning}
                    mr={"md"}
                >
                    <IconTrash />
                </ActionIcon>
            </>
        );
    };

    const palletButton = (label: string, onClick: () => void) => {
        return (
            <Button
                variant={"default"}
                onClick={onClick}
                disabled={isScanning}
                flex={1}
            >
                <Group gap={"md"}>
                    <IconPlus />
                    {label}
                </Group>
            </Button>
        );
    };

    const palletButtons = (pallet: ReceiptPallet) => {
        if (pallet.boxes.length > 0 || pallet.residualProducts.length > 0) {
            return;
        }
        return (
            <Flex gap={"md"}>
                {palletButton("Короб", () => createBox(pallet))}
                {palletButton("Товар", () => onObjectEditClick(pallet, false))}
            </Flex>
        );
    };

    const palletItem = (pallet: ReceiptPallet, palletIdx: number) => {
        return (
            <Accordion.Item key={pallet.id} value={pallet.id.toString()}>
                <Center>
                    <Accordion.Control icon={<IconSpace />}>
                        Паллет {pallet.id}
                    </Accordion.Control>
                    {palletActions(pallet)}
                </Center>
                <Accordion.Panel>
                    {palletButtons(pallet)}
                    {pallet.boxes &&
                        <Box pt={"md"}>
                            <AccordionBoxes pallet={pallet} palletIdx={palletIdx} />
                        </Box>
                    }
                    {pallet.residualProducts && (
                        <ReceiptProducts
                            products={pallet.residualProducts}
                            object={pallet}
                            setObjectData={object => setPalletData(object as ReceiptPallet)}
                            disabled={isScanning}
                        />
                    )}
                </Accordion.Panel>
            </Accordion.Item>
        );
    };

    if (pallets.length === 0) return;

    return (
        <Accordion multiple={true} bd={"solid 1px gray"}>
            {pallets.map(((pallet, idx) => palletItem(pallet, idx)))}
        </Accordion>
    );
};

export default AccordionPallets;
