import { ResidualBoxSchema } from "../../../../client";
import { Accordion, ActionIcon, Center, Checkbox, Text, Tooltip } from "@mantine/core";
import { IconBox, IconTrash } from "@tabler/icons-react";
import ResidualProductsTable from "../ResidualProductsTable/ResidualProductsTable.tsx";
import { useResiduesContext } from "../../contexts/ResiduesContext.tsx";

type Props = {
    boxes?: ResidualBoxSchema[];
}

const ResidualBoxes = ({ boxes }: Props) => {
    const { onDeleteBoxClick, boxIdsToPrint } = useResiduesContext();
    if (!boxes || boxes.length == 0) return;

    const boxIds = boxes.map((box) => box.id.toString());

    const removeBoxButton = (box: ResidualBoxSchema) => {
        return (
            <Tooltip label="Удалить короб">
                <ActionIcon
                    variant={"default"}
                    onClick={() => onDeleteBoxClick(box)}
                    mx={"md"}
                >
                    <IconTrash />
                </ActionIcon>
            </Tooltip>
        );
    };

    const checkboxToPrint = (box: ResidualBoxSchema) => {
        return (
            <Checkbox
                ml="sm"
                checked={boxIdsToPrint.has(box.id)}
                onChange={() => {
                    if (boxIdsToPrint.has(box.id)) {
                        boxIdsToPrint.delete(box.id);
                    } else {
                        boxIdsToPrint.add(box.id);
                    }
                }}
            />
        );
    };

    const renderBox = (box: ResidualBoxSchema) => {
        return (
            <Accordion.Item key={box.id} value={box.id.toString()}>
                <Center>
                    <Accordion.Control icon={<IconBox />}>
                        Короб {box.id}
                    </Accordion.Control>
                    {checkboxToPrint(box)}
                    {removeBoxButton(box)}
                </Center>
                <Accordion.Panel>
                    {
                        box.residualProducts.length > 0 ? (
                            <ResidualProductsTable
                                items={box.residualProducts.sort((a, b) => a.id - b.id)}
                            />
                        ) : (
                            <Text>Пустой</Text>
                        )
                    }
                </Accordion.Panel>
            </Accordion.Item>
        );
    };

    return (
        <Accordion
            multiple={true}
            defaultValue={boxIds}
            bd={"solid 1px gray"}
        >
            {boxes.sort((a, b) => a.id - b.id).map(box => renderBox(box))}
        </Accordion>
    );
};

export default ResidualBoxes;
