import {FC} from "react";
import styles from './ProductAndServiceTab.module.css';
import ProductView from "./components/ProductView/ProductView.tsx";
import {Button, Flex, ScrollArea, Title} from "@mantine/core";
import DealServicesTable from "./components/DealServicesTable/DealServicesTable.tsx";
import useDealProductAndServiceTabState from "./hooks/useProductAndServiceTabState.tsx";
import {modals} from "@mantine/modals";

const ProductAndServiceTab: FC = () => {
    const {dealState, dealServicesState, dealProductsState} = useDealProductAndServiceTabState();

    const onCreateProductClick = () => {
        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;
    }
    return (
        <div className={styles['container']}>

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

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

            </div>
            <div className={styles['deal-container']}>
                <Flex direction={"column"} className={styles['deal-container-wrapper']}>
                    <DealServicesTable
                        {...dealServicesState}
                    />
                    <div className={styles['deal-container-buttons']}>
                        <Button
                            onClick={onCreateProductClick}
                            variant={"default"}
                            fullWidth>Добавить товар</Button>
                    </div>
                </Flex>
                <Flex direction={"column"} className={styles['deal-container-wrapper']}>
                    <Title order={3}>Общая стоимость всех услуг: {getTotalPrice()}</Title>
                </Flex>
            </div>

        </div>
    )
}

export default ProductAndServiceTab;