// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck

import { ServiceSchema, ServiceService } from "../../../../client";
import { FC } from "react";
import { useServicesTableColumns } from "./columns.tsx";
import { BaseTable } from "../../../../components/BaseTable/BaseTable.tsx";
import { MRT_TableOptions } from "mantine-react-table";
import { CRUDTableProps } from "../../../../types/CRUDTable.tsx";
import { ActionIcon, Flex, Tooltip } from "@mantine/core";
import { IconArrowDown, IconArrowUp, IconEdit, IconTrash } from "@tabler/icons-react";
import { modals } from "@mantine/modals";
import { notifications } from "../../../../shared/lib/notifications.ts";
import { useQueryClient } from "@tanstack/react-query";
import { ServicesTab } from "../ServiceTypeSegmentedControl/ServiceTypeSegmentedControl.tsx";

type RestProps = {
    serviceType: ServicesTab;
    editMode: boolean;
}
type Props = CRUDTableProps<ServiceSchema> & RestProps;
const ServicesTable: FC<Props> = ({
                                      items,
                                      onDelete,
                                      onChange,
                                      serviceType,
                                      editMode,
                                  }) => {
    const queryClient = useQueryClient();
    const columns = useServicesTableColumns();
    const categoryRanks = items.map(item => item.category).map(category => {
        if (serviceType === ServicesTab.DEAL_SERVICE) {
            return category.cardServiceRank;
        }
        return category.productServiceRank;
    });
    const minRank = categoryRanks.sort()[0];
    const maxRank = categoryRanks.sort()[categoryRanks.length - 1];

    const onEditClick = (service: ServiceSchema) => {
        if (!onChange) return;
        modals.openContextModal({
            modal: "createService",
            title: "Создание услуги",
            withCloseButton: false,
            innerProps: {
                onChange: newService => onChange(newService),
                element: service,
            },
        });
    };
    return (
        <BaseTable
            data={items}
            columns={columns}

            restProps={{
                enableGrouping: true,
                initialState: {
                    grouping: ["category"],
                },
                state: {
                    columnVisibility: {
                        "mrt-row-drag": editMode,
                    },
                },
                enableColumnActions: false,
                enableRowOrdering: true,
                mantineRowDragHandleProps: ({ table }) => ({
                    onDragEnd: () => {
                        const { draggingRow, hoveredRow } = table.getState();
                        if (!hoveredRow?.original || !draggingRow?.original) return;
                        ServiceService.reorderService({
                            requestBody: {
                                drainingServiceId: draggingRow.original.id,
                                hoveredServiceId: hoveredRow.original.id,
                            },
                        }).then(({ ok, message }) => {
                            if (!ok) {
                                notifications.guess(ok, { message });
                                return;
                            }
                            queryClient.invalidateQueries({
                                queryKey: ["getAllServices"],
                            }).then(() => {
                            });
                        });
                    },
                }),
                displayColumnDefOptions: {
                    "mrt-row-drag": {
                        AggregatedCell: ({ row }) => {
                            const rank = serviceType === ServicesTab.DEAL_SERVICE ? row.original.category.cardServiceRank : row.original.category.productServiceRank;
                            return (
                                <Flex gap={"xs"}>
                                    <Tooltip label="Поднять вверх">
                                        <ActionIcon
                                            disabled={rank === minRank}
                                            onClick={() => {
                                                ServiceService.reorderServiceCategory({
                                                    requestBody: {
                                                        serviceType,
                                                        categoryId: row.original.category.id,
                                                        moveDown: false,
                                                        moveUp: true,
                                                    },
                                                }).then(({ ok, message }) => {
                                                    if (!ok) {
                                                        notifications.guess(ok, { message });
                                                        return;
                                                    }
                                                    queryClient.invalidateQueries({
                                                        queryKey: ["getAllServices"],
                                                    }).then(() => {
                                                    });
                                                });
                                            }}
                                            variant={"default"}>
                                            <IconArrowUp />
                                        </ActionIcon>
                                    </Tooltip>
                                    <Tooltip label="Опустить вниз">
                                        <ActionIcon
                                            disabled={rank === maxRank}
                                            onClick={() => {
                                                ServiceService.reorderServiceCategory({
                                                    requestBody: {
                                                        serviceType,
                                                        categoryId: row.original.category.id,
                                                        moveDown: true,
                                                        moveUp: false,
                                                    },
                                                }).then(({ ok, message }) => {
                                                    if (!ok) {
                                                        notifications.guess(ok, { message });
                                                        return;
                                                    }
                                                    queryClient.invalidateQueries({
                                                        queryKey: ["getAllServices"],
                                                    }).then(() => {
                                                    });
                                                });
                                            }}
                                            variant={"default"}>
                                            <IconArrowDown />
                                        </ActionIcon>
                                    </Tooltip>
                                </Flex>
                            );
                        },
                    },
                    "mrt-row-actions": {
                        AggregatedCell: ({ row }) => editMode && (
                            <Flex gap={"xs"}>
                                <Tooltip label={"Редактировать категорию"}>
                                    <ActionIcon onClick={() => {
                                        modals.openContextModal({
                                            modal: "createServiceCategory",
                                            title: "Создание категории",
                                            withCloseButton: false,
                                            innerProps: {
                                                element: row.original.category,
                                                onChange: newCategory => {
                                                    ServiceService.updateServiceCategory({ requestBody: { category: newCategory } }).then(({
                                                                                                                                               ok,
                                                                                                                                               message,
                                                                                                                                           }) => {
                                                            notifications.guess(ok, { message });
                                                            if (!ok) return;
                                                            queryClient.invalidateQueries({
                                                                queryKey: ["getAllServices"],
                                                            }).then(() => {
                                                            });
                                                        },
                                                    );
                                                },
                                            },
                                        });
                                    }} variant={"default"}>
                                        <IconEdit />
                                    </ActionIcon>
                                </Tooltip>
                                <Tooltip label={"Удалить категорию"}>
                                    <ActionIcon
                                        onClick={() => {
                                            modals.openConfirmModal({
                                                title: "Удаление категории",
                                                children: `Вы уверены, что хотите удалить категорию: ${row.original.category.name}?`,
                                                onConfirm: () => {
                                                    ServiceService.deleteServiceCategory({ requestBody: { categoryId: row.original.category.id } }).then(({
                                                                                                                                                              ok,
                                                                                                                                                              message,
                                                                                                                                                          }) => {
                                                        notifications.guess(ok, { message });
                                                        if (!ok) return;
                                                        queryClient.invalidateQueries({
                                                            queryKey: ["getAllServices"],
                                                        }).then(() => {
                                                        });
                                                    });
                                                },
                                            });
                                        }}
                                        variant={"default"}
                                    >
                                        <IconTrash />
                                    </ActionIcon>
                                </Tooltip>
                            </Flex>

                        ),
                    },
                },
                enableRowActions: true,
                renderRowActions: ({ row }) => (
                    <Flex display={row.original.isPlaceholder ? "none" : "flex"} gap="xs">
                        <Tooltip label="Редактировать">
                            <ActionIcon
                                onClick={() => onEditClick(row.original)}
                                variant={"default"}>
                                <IconEdit />
                            </ActionIcon>
                        </Tooltip>
                        <Tooltip label="Удалить">
                            <ActionIcon
                                onClick={() => {
                                    if (onDelete) onDelete(row.original);
                                }}
                                variant={"default"}>
                                <IconTrash />
                            </ActionIcon>
                        </Tooltip>
                    </Flex>
                ),
            } as MRT_TableOptions<ServiceSchema>
            }
        />
    );
};

export default ServicesTable;
