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

const Preview: FC = () => {
    const { selectedPrefillCard } = usePrefillCardContext();

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

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

                            <CardServicesTable items={selectedPrefillCard?.services} />

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

export default Preview;
