import { ActionIcon, Button, Flex, Stack, Text, Title } from "@mantine/core";
import useReceiptBox from "../hooks/useReceiptBox.tsx";
import ReceiptProducts from "./ReceiptProducts.tsx";
import InlineButton from "../../../../../components/InlineButton/InlineButton.tsx";
import { IconArrowLeft, IconBarcode, IconPlayerPause, IconPlus } from "@tabler/icons-react";

type Props = {
    boxId: number;
}

const ReceiptBoxEditor = ({ boxId }: Props) => {
    const {
        box,
        fetchBox,
        clientId,
        onCreateProductClick,
        scanningData,
        toggleScanning,
    } = useReceiptBox({ boxId });

    const { isScanning } = scanningData;

    if (!box) return <Text>Короб c ID K{boxId} не найден</Text>;

    const backButton = (
        <Button
            variant={"default"}
            onClick={() => window.location.reload()}
            flex={1}
            disabled={isScanning}
        >
            <IconArrowLeft />
        </Button>
    );

    const getScanningModeAction = () => {
        return (
            <ActionIcon
                variant={"default"}
                onClick={() => toggleScanning(box?.id)}
            >
                {isScanning ? (
                    <IconPlayerPause />
                ) : (
                    <IconBarcode />
                )}
            </ActionIcon>
        );
    };

    return (
        <Stack>
            <Flex align={"center"} justify={"space-between"}>
                <Flex align={"center"} flex={9} gap={"md"}>
                    {backButton}
                    <Title flex={8} order={3}>
                        Короб ID: К{box?.id}
                    </Title>
                </Flex>
                {getScanningModeAction()}
            </Flex>
            <InlineButton onClick={onCreateProductClick} disabled={isScanning}>
                <IconPlus />
                Товар
            </InlineButton>
            <ReceiptProducts
                object={box}
                clientId={clientId}
                updateObject={fetchBox}
                disabled={isScanning}
            />
        </Stack>
    );
};

export default ReceiptBoxEditor;
