import {
    Accordion,
    ActionIcon,
    Button,
    Center, Checkbox,
    Group,
    rem,
    ScrollArea,
    Stack,
    Text,
    Title,
    Tooltip,
} from "@mantine/core";
import { IconPlus, IconSpace, IconTrash } from "@tabler/icons-react";
import { useResiduesContext } from "../../contexts/ResiduesContext.tsx";
import { ResidualBoxSchema, ResidualPalletSchema, ResidualProductSchema } from "../../../../client";
import ResidualProductsTable from "../ResidualProductsTable/ResidualProductsTable.tsx";
import ResidualBoxes from "../ResidualBoxes/ResidualBoxes.tsx";
import residualBoxes from "../ResidualBoxes/ResidualBoxes.tsx";

const ResiduesTree = () => {
    const {
        selectedClient,
        onDeletePalletClick,
        onCreateBoxClick,
        palletIdsToPrint,
    } = useResiduesContext();
    const palletIds: string[] = [];

    const sortById = (data?: ResidualPalletSchema[] | ResidualBoxSchema[] | ResidualProductSchema[]) => {
        return data?.sort((a, b) => a.id - b.id);
    };

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

    const getPallets = () => {
        const sortedPallets = sortById(selectedClient?.pallets) as ResidualPalletSchema[];
        return sortedPallets?.map((pallet => {
            palletIds.push(pallet.id.toString());
            return (
                <Accordion.Item key={pallet.id} value={pallet.id.toString()}>
                    <Center>
                        <Accordion.Control icon={<IconSpace />}>
                            Паллет - П{pallet.id}
                        </Accordion.Control>
                        {checkboxToPrint(pallet)}
                        {removePalletButton(pallet)}
                    </Center>
                    <Accordion.Panel>
                        {getPalletContent(pallet)}
                    </Accordion.Panel>
                </Accordion.Item>
            );
        })) ?? [];
    };

    const removePalletButton = (pallet: ResidualPalletSchema) => {
        return (
            <Tooltip label="Удалить паллет">
                <ActionIcon
                    variant={"default"}
                    onClick={() => onDeletePalletClick(pallet)}
                    mx={"md"}
                >
                    <IconTrash />
                </ActionIcon>
            </Tooltip>
        );
    };

    const createBoxButton = (palletId: number) => {
        return (
            <Button
                variant={"default"}
                onClick={() => onCreateBoxClick(palletId)}
            >
                <Group gap={"md"}>
                    <IconPlus />
                    Добавить короб
                </Group>
            </Button>
        );
    };

    const getPalletContent = (pallet: ResidualPalletSchema) => {
        const isEmpty = pallet.boxes.length === 0 && pallet.residualProducts.length === 0;
        const isBox = pallet.residualProducts.length === 0;
        const title = isEmpty ? "Пустой" : isBox ? "Короба" : "Товары";

        const residualProducts = sortById(pallet.residualProducts) as ResidualProductSchema[];

        return (
            <Stack gap={rem(5)}>
                <Group justify={"space-between"}>
                    <Stack gap={"xs"}>
                        <Text>Дата добавления: {new Date(pallet.createdAt).toLocaleString("ru-RU")}</Text>
                        <Title order={6}>{title}</Title>
                    </Stack>
                    {isBox && createBoxButton(pallet.id)}
                </Group>
                {residualProducts.length > 0 && <ResidualProductsTable items={residualProducts} />}
                {residualBoxes.length > 0 && <ResidualBoxes boxes={pallet.boxes} />}
            </Stack>
        );
    };

    return (
        <ScrollArea>
            <Accordion
                multiple={true}
                defaultValue={palletIds}
                bd={"solid 1px gray"}
            >
                <ResidualBoxes boxes={selectedClient?.boxes} />
                {getPallets()}
            </Accordion>
        </ScrollArea>
    );
};

export default ResiduesTree;