import { useCardPageContext } from "../../../../../pages/CardsPage/contexts/CardPageContext.tsx";
import { Flex, rem, Stack } from "@mantine/core";
import { BoxSchema, PalletSchema, ShippingProductSchema } from "../../../../../client";
import ShippingProductsTable from "./ShippingProductsTable.tsx";
import BoxesTable from "./BoxesTable.tsx";
import { IconChevronRight, IconPlus, IconSpace, IconTrash } from "@tabler/icons-react";
import useShipping from "../hooks/useShipping.tsx";
import { DataTable } from "mantine-datatable";
import clsx from "clsx";
import "mantine-datatable/styles.css";
import classes from "../ShippingTab.module.css";
import InlineShippingButton from "./InlineShippingButton.tsx";

const ShippingTree = () => {
    const { selectedCard: card } = useCardPageContext();

    const {
        onCreateBoxInPallet,
        onCreateShippingProduct,
        onDeletePalletClick,
        palletIds,
        setPalletIds,
    } = useShipping();

    const sortById = (data?: PalletSchema[] | BoxSchema[] | ShippingProductSchema[]) => {
        return data?.sort((a, b) => a.id - b.id);
    };

    const removePalletButton = (pallet: PalletSchema) => {
        return (
            <InlineShippingButton onClick={() => onDeletePalletClick(pallet)}>
                <IconTrash />
            </InlineShippingButton>
        );
    };

    const createBoxOrShippingProductButton = (palletId: number, isBox: boolean) => {
        const createButtonLabel = isBox ? "Короб" : "Товар";

        return (
            <InlineShippingButton
                onClick={() => {
                    if (isBox) {
                        onCreateBoxInPallet(palletId);
                    } else {
                        onCreateShippingProduct({ palletId });
                    }
                }}
            >
                <IconPlus />
                {createButtonLabel}
            </InlineShippingButton>
        );
    };

    const getPalletContent = (pallet: PalletSchema) => {
        const isBox = pallet.boxes.length > 0;

        const boxes = sortById(pallet.boxes) as BoxSchema[];
        const shippingProducts = sortById(pallet.shippingProducts) as ShippingProductSchema[];

        if (isBox) {
            return (
                <BoxesTable items={boxes} onCreateShippingProduct={onCreateShippingProduct} />
            );
        }
        return (
            <ShippingProductsTable items={shippingProducts} />
        );
    };

    const getPalletActions = (pallet: PalletSchema) => {
        const isEmpty = pallet.boxes.length === 0 && pallet.shippingProducts.length === 0;
        const isBox = pallet.boxes.length > 0;

        let palletButtons;
        if (isEmpty) {
            palletButtons = [
                createBoxOrShippingProductButton(pallet.id, true),
                createBoxOrShippingProductButton(pallet.id, false),
            ];
        } else {
            palletButtons = [
                createBoxOrShippingProductButton(pallet.id, isBox),
            ];
        }

        return (
            <Flex
                gap={rem(10)}
                wrap={"nowrap"}
                direction={"row-reverse"}
            >
                {removePalletButton(pallet)}
                {...palletButtons}
            </Flex>
        );
    };

    const isPalletExpandable = (pallet: PalletSchema) => {
        const isExpandable = pallet.boxes.length !== 0 || pallet.shippingProducts.length !== 0;
        if (!isExpandable && palletIds.includes(pallet.id)) {
            setPalletIds(palletIds.filter(palletId => palletId !== pallet.id));
        }
        return isExpandable;
    };

    if (card?.boxes?.length === 0 && card?.pallets?.length === 0) {
        return;
    }

    return (
        <Stack gap={0}>
            {card?.boxes && (
                <BoxesTable items={card?.boxes} onCreateShippingProduct={onCreateShippingProduct} />
            )}
            <DataTable
                noHeader
                withTableBorder
                columns={[
                    {
                        accessor: "id",
                        title: "Паллет",
                        noWrap: true,
                        render: (pallet) => {
                            const isExpandable = isPalletExpandable(pallet);

                            return (
                                <>
                                    {isExpandable && (
                                        <IconChevronRight
                                            className={clsx(classes.icon, classes.expandIcon, {
                                                [classes.expandIconRotated]: palletIds?.includes(pallet.id),
                                            })}
                                        />
                                    )}
                                    <IconSpace className={classes.icon} />
                                    <span>Паллет П{pallet.id}</span>
                                </>
                            );
                        },
                    },
                    {
                        accessor: "actions",
                        title: "",
                        width: "0%",
                        render: getPalletActions,
                    },
                ]}
                records={card?.pallets?.sort((a, b) => a.id - b.id)}
                rowExpansion={{
                    allowMultiple: true,
                    expanded: { recordIds: palletIds, onRecordIdsChange: setPalletIds },
                    expandable: ({ record }) => isPalletExpandable(record),
                    content: ({ record }) => getPalletContent(record),
                }}
            />
        </Stack>
    );
};

export default ShippingTree;