import { FC } from "react";
import styles from "./Preview.module.css";
import { ScrollArea, Skeleton, Title } from "@mantine/core";
import DealServicesTable from "../tables/DealServicesTable/DealServicesTable.tsx";
import ProductPreview from "../ProductPreview/ProductPreview.tsx";
import { usePrefillDealContext } from "../../../../contexts/PrefillDealContext.tsx";

const Preview: FC = () => {
    const { selectedPrefillDeal } = usePrefillDealContext();

    const getTotalPrice = () => {
        if (!selectedPrefillDeal) return 0;
        const productServicesPrice = selectedPrefillDeal.products.reduce(
            (acc, row) =>
                acc +
                row.services.reduce(
                    (acc2, row2) => acc2 + row2.price * row.quantity,
                    0,
                ),
            0,
        );
        const dealServicesPrice = selectedPrefillDeal.services.reduce(
            (acc, row) => acc + row.price * row.quantity,
            0,
        );
        return dealServicesPrice + productServicesPrice;
    };

    return (
        <div className={styles["container"]}>
            <div className={styles["deal-container-wrapper"]}>
                <ScrollArea offsetScrollbars={"y"} w={"100%"}>
                    <div style={{ height: "93vh" }}>
                        <Skeleton visible={!selectedPrefillDeal}>
                            <Title order={4} mb={18}>
                                Общая стоимость всех услуг:{" "}
                                {getTotalPrice().toLocaleString("ru")}₽
                            </Title>

                            <DealServicesTable items={selectedPrefillDeal?.services} />

                            <div className={styles["products-list"]}>
                                {selectedPrefillDeal?.products.map(product => (
                                    <ProductPreview
                                        key={product.product.id}
                                        product={product}
                                    />
                                ))}
                            </div>
                        </Skeleton>
                    </div>
                </ScrollArea>
            </div>
        </div>
    );
};

export default Preview;
