import { CRUDTableProps } from "../../../../types/CRUDTable.tsx";
import { CardService, CardSummary } from "../../../../client";
import { FC } from "react";
import useCardsTableColumns from "./columns.tsx";
import { BaseTable } from "../../../../components/BaseTable/BaseTable.tsx";
import { ActionIcon, Flex, Tooltip } from "@mantine/core";
import { IconEdit } from "@tabler/icons-react";
import { MRT_TableOptions } from "mantine-react-table";
import { useCardPageContext } from "../../contexts/CardPageContext.tsx";

type RestProps = {
    viewOnly?: boolean;
};
type Props = CRUDTableProps<CardSummary> & RestProps;

const CardsTable: FC<Props> = ({ items, onSelectionChange, viewOnly = false }) => {
    const columns = useCardsTableColumns();
    const { setSelectedCard } = useCardPageContext();
    const onEditClick = (cardSummary: CardSummary) => {
        CardService.getCardById({ cardId: cardSummary.id }).then(card => {
            setSelectedCard(card);
        });
    };

    return (
        <BaseTable
            data={items}
            columns={columns}
            onSelectionChange={onSelectionChange}
            restProps={
                {
                    enableSorting: true,
                    enableColumnActions: false,
                    enablePagination: !viewOnly,
                    enableBottomToolbar: !viewOnly,
                    paginationDisplayMode: "pages",
                    enableRowActions: true,
                    enableRowSelection: true,
                    renderRowActions: ({ row }) => (
                        <Flex gap="md">
                            <Tooltip label="Редактировать">
                                <ActionIcon
                                    disabled={viewOnly}
                                    onClick={() => onEditClick(row.original)}
                                    variant={"default"}>
                                    <IconEdit />
                                </ActionIcon>
                            </Tooltip>
                        </Flex>
                    ),
                } as MRT_TableOptions<CardSummary>
            }
        />
    );
};

export default CardsTable;
