import { ContextModalProps } from "@mantine/modals";
import { BaseTransactionTagSchema, TransactionService, TransactionTagSchema } from "../../../../../client";
import useTransactionTagsList from "../../../hooks/useTransactionTagsList.tsx";
import TransactionTagsTable from "../components/TransactionTagsTable.tsx";
import { useCRUD } from "../../../../../hooks/useCRUD.tsx";
import { notifications } from "../../../../../shared/lib/notifications.ts";

type Props = {
    onChange: () => Promise<void>;
    isIncome: boolean;
};

const TransactionTagsModal = ({
                              innerProps,
                          }: ContextModalProps<Props>) => {
    const { onChange: onTagChange } = innerProps;
    const { objects: expenseTags, refetch } = useTransactionTagsList({ isIncome: innerProps.isIncome });

    const crud = useCRUD<TransactionTagSchema, BaseTransactionTagSchema>({
        onChange: tag => {
            TransactionService.updateTransactionTag({
                requestBody: {
                    tag,
                },
            })
                .then(async ({ ok, message }) => {
                    notifications.guess(ok, { message });
                    if (!ok) return;
                    await refetch();
                    await onTagChange();
                })
                .catch(err => console.log(err));
        },
        onCreate: tag => {
            TransactionService.createTransactionTag({
                requestBody: {
                    tag: {
                        ...tag,
                        isIncome: innerProps.isIncome,
                    }
                },
            })
                .then(async ({ ok, message }) => {
                    notifications.guess(ok, { message });
                    if (!ok) return;
                    await refetch();
                    await onTagChange();
                })
                .catch(err => console.log(err));
        },
        onDelete: (tag) => {
            TransactionService.deleteTransactionTag({
                tagId: tag.id,
            })
                .then(async ({ ok, message }) => {
                    notifications.guess(ok, { message });
                    if (!ok) return;
                    await refetch();
                })
                .catch(err => console.log(err));
        },
    });

    return (
        <TransactionTagsTable
            {...crud}
            items={expenseTags}
            isIncome={innerProps.isIncome}
        />
    );
};

export default TransactionTagsModal;
