import { BoxSchema, ShippingService } from "../../../../../client";
import { IconBox, IconChevronRight, IconPlus, IconTrash } from "@tabler/icons-react";
import useUpdateCard from "../hooks/useUpdateCard.tsx";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import { DataTable } from "mantine-datatable";
import clsx from "clsx";
import classes from "../ShippingTab.module.css";
import "mantine-datatable/styles.css";
import { useState } from "react";
import ShippingProductsTable from "./ShippingProductsTable.tsx";
import { Flex, rem, Text } from "@mantine/core";
import { ShippingProductParentData } from "../types/ShippingProductData.tsx";
import { modals } from "@mantine/modals";
import InlineShippingButton from "./InlineShippingButton.tsx";


type Props = {
    items: BoxSchema[];
    onCreateShippingProduct: (values: ShippingProductParentData) => void;
}

const BoxesTable = ({ items, onCreateShippingProduct }: Props) => {
    const { update } = useUpdateCard();
    const [boxIds, setBoxIds] = useState<number[]>([]);

    const onDeleteBox = (boxId: number) => {
        ShippingService.deleteBox({
            boxId,
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                if (ok) update();
            })
            .catch(err => console.log(err));
    };

    const onDeleteBoxClick = (box: BoxSchema) => {
        if (box.shippingProducts.length === 0) {
            onDeleteBox(box.id);
            return;
        }

        modals.openConfirmModal({
            title: "Удаление короба",
            children: <Text size="sm">Вы уверены что хотите удалить короб?</Text>,
            labels: { confirm: "Да", cancel: "Нет" },
            confirmProps: { color: "red" },
            onConfirm: () => onDeleteBox(box.id),
        });
    };

    const getBoxContent = (box: BoxSchema) => {
        if (box.shippingProducts.length === 0) {
            return (
                <Text>Пустой</Text>
            );
        }

        return (
            <ShippingProductsTable items={box.shippingProducts} />
        );
    };

    const getBoxActions = (box: BoxSchema) => {
        return (
            <Flex wrap={"nowrap"} direction={"row-reverse"} gap={rem(10)}>
                <InlineShippingButton onClick={() => onDeleteBoxClick(box)}>
                    <IconTrash />
                </InlineShippingButton>
                <InlineShippingButton onClick={() => onCreateShippingProduct({ boxId: box.id })}>
                    <IconPlus />
                    Товар
                </InlineShippingButton>
            </Flex>
        );
    };

    const isBoxExpandable = (box: BoxSchema) => {
        const isExpandable = box.shippingProducts.length > 0;
        if (!isExpandable && boxIds.includes(box.id)) {
            setBoxIds(boxIds.filter(boxId => boxId !== box.id));
        }
        return isExpandable;
    };

    return (
        <DataTable
            noHeader
            withTableBorder
            columns={[
                {
                    accessor: "id",
                    title: "Короб",
                    noWrap: true,
                    render: (box) => (
                        <>
                            {isBoxExpandable(box) && (
                                <IconChevronRight
                                    className={clsx(classes.icon, classes.expandIcon, {
                                        [classes.expandIconRotated]: boxIds?.includes(box.id),
                                    })}
                                />
                            )}
                            <IconBox className={classes.icon} />
                            <span>Короб К{box.id}</span>
                        </>
                    ),
                },
                {
                    accessor: "actions",
                    title: "",
                    width: "0%",
                    render: getBoxActions,
                },
            ]}
            records={items?.sort((a, b) => a.id - b.id)}
            rowExpansion={{
                allowMultiple: true,
                expanded: { recordIds: boxIds, onRecordIdsChange: setBoxIds },
                expandable: ({ record }) => isBoxExpandable(record),
                content: ({ record }) => getBoxContent(record),
            }}
        />
    );
};

export default BoxesTable;
