import {Drawer, Text} from "@mantine/core";
import {FC, useRef} from "react";
import DealServicesTable from "../../components/DealServicesTable/DealServicesTable.tsx";
import {useDealPageContext} from "../../contexts/DealPageContext.tsx";
import {DealService, DealServiceSchema} from "../../../../client";
import {notifications} from "../../../../shared/lib/notifications.ts";
import {modals} from "@mantine/modals";
import {BaseTableRef} from "../../../../components/BaseTable/BaseTable.tsx";
import DealProductsTable from "../../components/DealProductsTable/DealProductsTable.tsx";

const useDealServicesTableState = () => {
    const {selectedDeal, setSelectedDeal} = useDealPageContext();
    const tableRef = useRef<BaseTableRef<DealServiceSchema>>(null);

    const onServiceUpdate = (service: DealServiceSchema) => {
        if (!selectedDeal) return;
        DealService.updateDealServiceQuantity({
            requestBody: {
                dealId: selectedDeal.id,
                serviceId: service.service.id,
                quantity: service.quantity
            }
        }).then(async ({ok, message}) => {

            if (!ok) {
                notifications.guess(ok, {message});
                return;
            }
            await DealService.getDealById({dealId: selectedDeal.id})
                .then(setSelectedDeal)
        })
    }

    const onServiceDelete = (service: DealServiceSchema) => {
        if (!selectedDeal) return;
        modals.openConfirmModal({
            title: "Удаление услуги",
            children: (
                <>
                    <Text>
                        Вы уверены, что хотите удалить услугу:
                    </Text>
                    <Text>
                        {service.service.name}?
                    </Text>

                </>

            ),
            onConfirm: () => {
                DealService.deleteDealService({
                    requestBody: {
                        dealId: selectedDeal.id,
                        serviceId: service.service.id
                    }
                }).then(async ({ok, message}) => {
                    if (!ok) {
                        notifications.guess(ok, {message});
                        return;
                    }
                    await DealService.getDealById({dealId: selectedDeal.id})
                        .then(setSelectedDeal)
                })
            },
            labels: {
                cancel: "Отмена",
                confirm: "Удалить"
            }
        })
    }

    const onServiceCreate = (service: DealServiceSchema) => {
        console.log('-------Drawer')
        console.log(service);
        if (!selectedDeal) return;
        DealService.addDealService({
            requestBody: {
                dealId: selectedDeal.id,
                serviceId: service.service.id,
                quantity: service.quantity
            }
        }).then(async ({ok, message}) => {
            if (!ok) {
                notifications.guess(ok, {message});
                return;
            }
            await DealService.getDealById({dealId: selectedDeal.id})
                .then(setSelectedDeal)
        })
    }

    const onsServiceMultipleDelete = (items: DealServiceSchema[]) => {
        if (!selectedDeal) return;
        modals.openConfirmModal({
            title: "Удаление услуг",
            children: (
                <>
                    <Text>
                        Вы уверены, что хотите удалить выбранные услуги?
                    </Text>
                </>
            ),
            onConfirm: () => {
                DealService.deleteMultipleDealServices({
                    requestBody: {
                        dealId: selectedDeal.id,
                        serviceIds: items.map(item => item.service.id)
                    }
                }).then(async ({ok, message}) => {
                    if (!ok) {
                        notifications.guess(ok, {message});
                        return;
                    }
                    await DealService.getDealById({dealId: selectedDeal.id})
                        .then(setSelectedDeal)
                })
            },
            labels: {
                cancel: "Отмена",
                confirm: "Удалить"
            }
        })
    }

    return {
        onServiceUpdate,
        onServiceDelete,
        onServiceCreate,
        onsServiceMultipleDelete,
        tableRef,
        services: selectedDeal?.services || []
    }
}
const DealEditDrawerServicesTable = () => {
    const {
        services,
        tableRef,
        onServiceCreate,
        onServiceUpdate,
        onServiceDelete,
        onsServiceMultipleDelete
    } = useDealServicesTableState();

    return (<DealServicesTable
        tableRef={tableRef}
        items={services}
        onChange={onServiceUpdate}
        onDelete={onServiceDelete}
        onCreate={onServiceCreate}
        onMultipleDelete={onsServiceMultipleDelete}
    />)
}

const useDealProductTableState = () => {
    const {selectedDeal} = useDealPageContext();

    return {
        clientId: selectedDeal?.clientId || -1,
        products: selectedDeal?.products || []
    }
}

const DealEditDrawerProductsTable = () => {
    const {
        products,
        clientId
    } = useDealProductTableState();
    return (
        <DealProductsTable
            clientId={clientId}
            items={products}
        />
    )
}

const useDealEditDrawerState = () => {
    const {selectedDeal, setSelectedDeal} = useDealPageContext();
    return {
        isVisible: selectedDeal !== undefined,
        onClose: () => setSelectedDeal(undefined)
    }
}

const DealEditDrawer: FC = () => {
    const {isVisible, onClose} = useDealEditDrawerState();

    return (
        <Drawer
            size={"95%"}
            position={"right"}
            onClose={onClose}
            opened={isVisible}>
            <DealEditDrawerServicesTable/>
            <DealEditDrawerProductsTable/>
        </Drawer>
    );
}

export default DealEditDrawer;