import {FC} from "react";
import styles from './ProductAndServiceTab.module.css';
import ProductView from "./components/ProductView/ProductView.tsx";
import {Button, Divider, Flex, rem, ScrollArea, Text, Title} from "@mantine/core";
import DealServicesTable from "./components/DealServicesTable/DealServicesTable.tsx";
import useDealProductAndServiceTabState from "./hooks/useProductAndServiceTabState.tsx";
import {modals} from "@mantine/modals";
import {
    BillingService,
    DealProductSchema,
    DealService,
    GetServiceKitSchema,
    ProductSchema,
    ProductService
} from "../../../../client";
import {notifications} from "../../../../shared/lib/notifications.ts";
import {CreateProductRequest} from "../../../ProductsPage/types.ts";
import classNames from "classnames";

const ProductAndServiceTab: FC = () => {
    const {dealState, dealServicesState, dealProductsState} = useDealProductAndServiceTabState();
    const isLocked = Boolean(dealState.deal?.billRequest);
    const onAddProductClick = () => {
        if (!dealProductsState.onCreate || !dealState.deal) return;
        const productIds = dealState.deal.products.map(product => product.product.id);
        modals.openContextModal({
            modal: "addDealProduct",
            innerProps: {
                onCreate: dealProductsState.onCreate,
                clientId: dealState.deal.clientId,
                productIds: productIds
            },
            withCloseButton: false
        })
    }
    const getTotalPrice = () => {
        if (!dealState.deal) return 0
        const productServicesPrice = dealState.deal.products.reduce((acc, row) => acc + row.services.reduce((acc2, row2) => acc2 + row2.price * row.quantity, 0), 0);
        const dealServicesPrice = dealState.deal.services.reduce((acc, row) => acc + row.price * row.quantity, 0);
        return dealServicesPrice + productServicesPrice;
    }
    const onCopyServices = (
        sourceProduct: DealProductSchema,
        destinationProducts: DealProductSchema[]
    ) => {
        if (!dealState.deal) return;
        DealService.copyProductServices({
            requestBody: {
                dealId: dealState.deal.id,
                destinationProductIds: destinationProducts.map(product => product.product.id),
                sourceProductId: sourceProduct.product.id
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await dealState.refetch()
        })
    }
    const onCopyServicesClick = (product: DealProductSchema) => {
        modals.openContextModal({
            modal: "selectDealProductsModal",
            title: "Дублирование услуг",
            size: "lg",
            innerProps: {
                dealProducts: dealState.deal?.products || [],
                dealProduct: product,
                onSelect: onCopyServices
            },
            withCloseButton: false
        })
    }

    const onKitAdd = (item: DealProductSchema, kit: GetServiceKitSchema) => {
        if (!dealState.deal) return;
        DealService.addKitToDealProduct({
            requestBody: {
                dealId: dealState.deal.id,
                kitId: kit.id,
                productId: item.product.id
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await dealState.refetch();
        });
    }
    const onDealKitAdd = (kit: GetServiceKitSchema) => {
        if (!dealState.deal) return;
        DealService.addKitToDeal({
            requestBody: {
                dealId: dealState.deal.id,
                kitId: kit.id,
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await dealState.refetch();
        });
    }

    const onCreateProduct = (newProduct: CreateProductRequest) => {
        ProductService.createProduct({
            requestBody: newProduct
        }).then(({ok, message}) => {
            notifications.guess(ok, {message: message});
        })
    }
    const onCreateProductClick = () => {
        if (!dealState.deal) return;
        modals.openContextModal({
            modal: "createProduct",
            title: 'Создание товара',
            withCloseButton: false,
            innerProps: {
                clientId: dealState.deal.clientId,
                onCreate: onCreateProduct
            }
        })
    }
    const onProductEdit = (product: ProductSchema) => {
        ProductService.updateProduct({requestBody: {product}})
            .then(async ({ok, message}) => {
                notifications.guess(ok, {message});
                if (!ok) return;
                await dealState.refetch();
            })
    }

    const onCreateBillClick = () => {
        if (!dealState.deal) return;
        const dealId = dealState.deal.id;
        modals.openConfirmModal({
            withCloseButton: false,
            size: "xl",
            children:
                <Text style={{textAlign: "justify"}}>
                    Создание заявки на выставление счета, подтвержденное нажатием кнопки "Выставить", заблокирует
                    возможность
                    редактирования товаров и услуг сделки. Пожалуйста, проверьте всю информацию на точность и полноту
                    перед подтверждением.
                </Text>,
            onConfirm: () => {
                BillingService.createDealBill({
                    requestBody: {
                        dealId
                    }
                }).then(async ({ok, message}) => {
                    notifications.guess(ok, {message});
                    if (ok) notifications.success({message: "Ссылка на оплату доступна во вкладе общее"});
                    await dealState.refetch();
                })
            },
            labels: {
                confirm: "Выставить",
                cancel: "Отмена"
            }
        });
    }
    const onCancelBillClick = () => {
        if (!dealState.deal) return;
        const dealId = dealState.deal.id;
        modals.openConfirmModal({
            withCloseButton: false,
            children:
                <Text style={{textAlign: "justify"}}>
                    Вы уверены что хотите отозвать заявку на оплату?
                </Text>,
            onConfirm: () => {
                BillingService.cancelDealBill({
                    requestBody: {
                        dealId
                    }
                }).then(async ({ok, message}) => {
                    notifications.guess(ok, {message});
                    await dealState.refetch();
                })
            },
            labels: {
                confirm: "Отозвать",
                cancel: "Отмена"
            },

        });
    }
    return (
        <div
            className={
                classNames(styles['container'],
                    dealState.deal?.billRequest && styles['container-disabled']
                )
            }>

            <div className={styles['products-list']}>
                <ScrollArea offsetScrollbars>

                    {dealState.deal?.products.map(product => (
                        <ProductView
                            onProductEdit={onProductEdit}
                            onKitAdd={onKitAdd}
                            onCopyServices={onCopyServicesClick}
                            key={product.product.id}
                            product={product}
                            onChange={dealProductsState.onChange}
                            onDelete={dealProductsState.onDelete}
                        />
                    ))}
                </ScrollArea>

            </div>

            <div className={styles['deal-container']}>
                <ScrollArea offsetScrollbars>

                    <Flex direction={"column"} className={styles['deal-container-wrapper']}>
                        <DealServicesTable
                            onKitAdd={onDealKitAdd}
                            {...dealServicesState}
                        />

                        <Divider my={rem(15)}/>
                        <div className={styles['deal-container-buttons']}>
                            <Button
                                disabled={isLocked}

                                variant={"default"}
                                fullWidth
                                onClick={onCreateProductClick}
                            >Создать товар</Button>
                            <Button
                                disabled={isLocked}

                                onClick={onAddProductClick}
                                variant={"default"}
                                fullWidth>Добавить товар</Button>
                        </div>
                        <Divider my={rem(15)}/>
                        <div className={styles['deal-container-buttons']}>
                            {isLocked ? <Button
                                    onClick={onCancelBillClick}
                                    color={"red"}
                                >
                                    Отозвать счет
                                </Button> :
                                <Button
                                    disabled={isLocked}
                                    onClick={onCreateBillClick}
                                    variant={"default"}
                                    fullWidth>Выставить счет</Button>
                            }

                        </div>

                    </Flex>
                    <Flex direction={"column"} className={styles['deal-container-wrapper']}>
                        <Title order={3}>Общая стоимость всех услуг: {getTotalPrice().toLocaleString("ru")}₽</Title>
                    </Flex>
                </ScrollArea>

            </div>

        </div>
    )
}

export default ProductAndServiceTab;