import {FC, useEffect, useState} from "react";
import {ActionIcon, Button, Flex, Pagination, rem, Text, Tooltip} from "@mantine/core";
import {usePaymentRecordsList} from "../../../../hooks/usePaymentRecordsList.tsx";
import {BaseTable} from "../../../../components/BaseTable/BaseTable.tsx";
import {usePaymentRecordsTableColumns} from "./columns.tsx";
import {modals} from "@mantine/modals";
import {PaymentRecordCreateSchema, PaymentRecordGetSchema, PayrollService} from "../../../../client";
import {notifications} from "../../../../shared/lib/notifications.ts";
import {IconTrash} from "@tabler/icons-react";
import {MRT_TableOptions} from "mantine-react-table";
import {formatDate} from "../../../../types/utils.ts";

const PaymentRecordsTable: FC = () => {
    const [totalPages, setTotalPages] = useState(10);
    const [page, setPage] = useState(1);
    const {
        pagination: paginationInfo,
        objects: paymentRecords,
        refetch
    } = usePaymentRecordsList({page: page, itemsPerPage: 10});
    useEffect(() => {
        if (!paginationInfo) return;
        setTotalPages(paginationInfo.totalPages);
    }, [paginationInfo]);

    const onCreate = (request: PaymentRecordCreateSchema) => {
        PayrollService.createPaymentRecord({
            requestBody: {
                data: request
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await refetch();
        })
    }
    const onCreateClick = () => {
        modals.openContextModal({
            modal: "createPaymentRecord",
            title: "Создание начисления",
            innerProps: {
                onCreate: onCreate
            },
        })
    }
    const onDelete = (record: PaymentRecordGetSchema) => {
        PayrollService.deletePaymentRecord({
            requestBody: {
                paymentRecordId: record.id
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await refetch();
        })
    }
    const onDeleteClick = (record: PaymentRecordGetSchema) => {
        modals.openConfirmModal({
            title: 'Удаление начисления',
            children: (
                <Text size="sm">
                    Вы уверены что хотите удалить начисление
                    пользователю {record.user.firstName} {record.user.secondName} от {formatDate(record.createdAt)}
                </Text>
            ),
            labels: {confirm: 'Да', cancel: "Нет"},
            confirmProps: {color: 'red'},
            onConfirm: () => onDelete(record)
        })
    }
    const columns = usePaymentRecordsTableColumns();
    return (
        <Flex
            direction={"column"}
            h={"100%"}
            gap={rem(10)}
        >
            <BaseTable
                data={paymentRecords}
                columns={columns}
                restProps={{
                    enableSorting: false,
                    enableColumnActions: false,
                    enableTopToolbar: true,
                    renderTopToolbar: (
                        <Flex p={rem(10)}>

                            <Button
                                variant={"default"}
                                onClick={() => onCreateClick()}
                            >
                                Создать начисление
                            </Button>
                        </Flex>
                    ),
                    enableRowActions: true,
                    renderRowActions: ({row}) => (
                        <Flex gap="md">

                            <Tooltip label="Удалить">
                                <ActionIcon onClick={() => onDeleteClick(row.original)} variant={"default"}>
                                    <IconTrash/>
                                </ActionIcon>
                            </Tooltip>
                        </Flex>
                    )
                } as MRT_TableOptions<PaymentRecordGetSchema>}
            />
            {totalPages > 1 &&

                <Pagination
                    style={{alignSelf: "flex-end"}}
                    withEdges
                    onChange={event => setPage(event)}
                    value={page}
                    total={totalPages}
                />
            }

        </Flex>
    )
}
export default PaymentRecordsTable;