import {CRUDTableProps} from "../../../../types/CRUDTable.tsx";
import {DealService, DealSummary} from "../../../../client";
import {FC} from "react";
import useDealsTableColumns 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 {useDealPageContext} from "../../../LeadsPage/contexts/DealPageContext.tsx";

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

const DealsTable: FC<Props> = ({items, viewOnly = false}) => {
    const columns = useDealsTableColumns();
    const {setSelectedDeal} = useDealPageContext();
    const onEditClick = (dealSummary: DealSummary) => {
        DealService.getDealById({dealId: dealSummary.id})
            .then((deal) => {
                setSelectedDeal(deal);
            })
    }
    return (
        <BaseTable
            data={items}
            columns={columns}
            restProps={{
                enableSorting: true,
                enableColumnActions: false,
                enablePagination: !viewOnly,
                enableBottomToolbar: !viewOnly,
                paginationDisplayMode: "pages",
                enableRowActions: true,
                renderRowActions: ({row}) => (
                    <Flex gap="md">
                        <Tooltip label="Редактировать">
                            <ActionIcon
                                disabled={viewOnly}
                                onClick={() => onEditClick(row.original)}
                                variant={"default"}>
                                <IconEdit/>
                            </ActionIcon>
                        </Tooltip>
                    </Flex>
                )
            } as MRT_TableOptions<DealSummary>}
        />
    )
}

export default DealsTable;