import { useTransactionsList } from "../../hooks/useTransactionsList.tsx";
import { useTransactionsTableColumns } from "./hooks/useTransactionsTableColumns.tsx";
import { TransactionSchemaBase, TransactionService } from "../../../../client";
import { dateToString } from "../../../../types/utils.ts";
import { notifications } from "../../../../shared/lib/notifications.ts";
import { modals } from "@mantine/modals";
import { BaseTable } from "../../../../components/BaseTable/BaseTable.tsx";
import { ActionIcon, Button, Flex, Pagination, rem, Tooltip } from "@mantine/core";
import { useEffect, useState } from "react";
import { IconEdit, IconTrash } from "@tabler/icons-react";
import { MRT_TableOptions } from "mantine-react-table";
import { Transaction } from "./types/Transaction.tsx";
import { TransactionsSegmentedControl, TransactionType } from "./components/TransactionsSegmentedControl.tsx";


export const TransactionsTab = () => {
    const [transactionType, setTransactionType] = useState<TransactionType>(TransactionType.EXPENSE);
    const isIncome = transactionType === TransactionType.INCOME;

    const [totalPages, setTotalPages] = useState(10);
    const [page, setPage] = useState(1);
    const {
        pagination: paginationInfo,
        objects: transactions,
        refetch,
    } = useTransactionsList({ page: page, itemsPerPage: 10, isIncome });
    const columns = useTransactionsTableColumns();

    useEffect(() => {
        if (!paginationInfo) return;
        if (!paginationInfo.totalPages) setTotalPages(0);
        else setTotalPages(paginationInfo.totalPages);
    }, [paginationInfo]);

    const onUpdate = (transaction: Transaction) => {
        TransactionService.updateTransaction({
            requestBody: {
                transaction: {
                    ...transaction,
                    spentDate: dateToString(new Date(transaction.spentDate)) ?? "",
                    isIncome,
                },
            },
        })
            .then(async ({ ok, message }) => {
                notifications.guess(ok, { message });
                await refetch();
            })
            .catch(err => console.log(err));
    };

    const modalTitleSuffix = isIncome ? "доходах" : "расходах";

    const onCreateClick = () => {
        modals.openContextModal({
            modal: "transactionFormModal",
            title: `Создание записи о ${modalTitleSuffix}`,
            withCloseButton: false,
            innerProps: {
                onCreate: onUpdate,
                isIncome,
            },
        });
    };

    const onEditClick = (transaction: TransactionSchemaBase) => {
        const expenseToEdit = { ...transaction, tags: transaction.tags.map(tag => tag.name) };
        modals.openContextModal({
            modal: "transactionFormModal",
            title: `Редактирование записи о ${modalTitleSuffix}`,
            withCloseButton: false,
            innerProps: {
                onChange: onUpdate,
                element: expenseToEdit,
                isIncome,
            },
        });
    };

    const onDeleteClick = (transaction: TransactionSchemaBase) => {
        TransactionService.deleteTransaction({
            transactionId: transaction.id,
        })
            .then(async ({ ok, message }) => {
                notifications.guess(ok, { message });
                await refetch();
            })
            .catch(err => console.log(err));
    };

    const onTagChange = async () => {
        await refetch();
    };

    const onTagsEditClick = () => {
        modals.openContextModal({
            modal: "transactionTagsModal",
            title: "Редактирование тегов",
            withCloseButton: false,
            innerProps: {
                onChange: onTagChange,
                isIncome,
            },
        });
    };

    const getCreateTransactionLabel = (): string => {
        if (transactionType === TransactionType.EXPENSE) {
            return "Создать запись о расходах";
        }
        return "Создать запись о доходах";
    };

    const getEditTagLabel = (): string => {
        if (transactionType === TransactionType.EXPENSE) {
            return "Редактировать теги для расходов";
        }
        return "Редактировать теги для доходов";
    };

    return (
        <Flex
            direction={"column"}
            h={"100%"}
            gap={0}>
            <TransactionsSegmentedControl
                value={transactionType.toString()}
                onChange={event => {
                    setPage(1);
                    setTransactionType(parseInt(event));
                }}
            />
            <BaseTable
                data={transactions}
                columns={columns}
                restProps={
                    {
                        enableTopToolbar: true,
                        enableRowActions: true,
                        enableSorting: false,
                        enableColumnActions: false,
                        renderTopToolbar: (
                            <Flex p={rem(10)} gap={rem(10)}>
                                <Button
                                    variant={"default"}
                                    onClick={() => onCreateClick()}>
                                    {getCreateTransactionLabel()}
                                </Button>
                                <Button
                                    variant={"default"}
                                    onClick={() => onTagsEditClick()}>
                                    {getEditTagLabel()}
                                </Button>
                            </Flex>
                        ),
                        renderRowActions: ({ row }) => (
                            <Flex gap="md">
                                <Tooltip label="Редактировать">
                                    <ActionIcon
                                        onClick={() => onEditClick(row.original)}
                                        variant={"default"}>
                                        <IconEdit />
                                    </ActionIcon>
                                </Tooltip>
                                <Tooltip label="Удалить">
                                    <ActionIcon
                                        onClick={() => onDeleteClick(row.original)}
                                        variant={"default"}>
                                        <IconTrash />
                                    </ActionIcon>
                                </Tooltip>
                            </Flex>
                        ),
                    } as MRT_TableOptions<TransactionSchemaBase>
                }
            />
            {totalPages > 1 && (
                <Pagination
                    style={{ alignSelf: "flex-end" }}
                    withEdges
                    onChange={event => setPage(event)}
                    value={page}
                    total={totalPages}
                />
            )}
        </Flex>
    );
};