import { FC } from "react";
import { Flex, ScrollArea, Stack } from "@mantine/core";
import { modals } from "@mantine/modals";
import BaseTable from "@/components/ui/BaseTable/BaseTable";
import { DealServiceSchema } from "@/lib/client";
import AddDealServiceButton from "@/modules/dealModularEditorTabs/FulfillmentBase/mobile/components/AddDealServiceButton/AddDealServiceButton";
import useDealServicesTableColumns from "@/modules/dealModularEditorTabs/FulfillmentBase/mobile/components/DealServiceTable/useDealServicesTableColumns";
import DealServicesTotalLabel from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/components/DealServicesTotalLabel/DealServicesTotalLabel";
import { useFulfillmentBaseContext } from "../../../shared/contexts/FulfillmentBaseContext";

const DealServicesTable: FC = () => {
    const { dealServicesList, dealServicesCrud } = useFulfillmentBaseContext();

    const onChange = (item: DealServiceSchema) => {
        const serviceIdsToExclude = dealServicesList.dealServices.map(
            dealService => dealService.service.id
        );

        modals.openContextModal({
            modal: "dealServiceEditorModal",
            innerProps: {
                entity: item,
                onChange: values =>
                    dealServicesCrud.onUpdate(
                        item.dealId,
                        item.serviceId,
                        values
                    ),
                serviceIdsToExclude,
                isEditing: true,
            },
            withCloseButton: false,
        });
    };

    const columns = useDealServicesTableColumns({
        onDelete: dealServicesCrud.onDelete,
        onChange,
    });

    return (
        <ScrollArea
            m={"xs"}
            h={"calc(100vh - 140px)"}
            scrollbars={"y"}
            type={"scroll"}>
            <Stack gap={"sm"}>
                <Flex
                    p={"sm"}
                    bd={"1px solid var(--mantine-color-default-border)"}
                    bdrs={"lg"}>
                    <DealServicesTotalLabel order={5} />
                </Flex>
                <BaseTable
                    records={dealServicesList.dealServices}
                    columns={columns}
                    groups={undefined}
                    idAccessor={"serviceId"}
                    withTableBorder
                />
                <AddDealServiceButton size={"lg"} />
            </Stack>
        </ScrollArea>
    );
};
export default DealServicesTable;
