import styles from "../PrefillDealsWithExcelDrawer.module.css";
import ProductsTable from "./ProductsTable.tsx";
import { usePrefillDealsWithExcelContext } from "../../../contexts/PrefillDealsWithExcelContext.tsx";
import { Box, Button, Flex, Group, Stack, Title } from "@mantine/core";
import { ProductExcelData } from "../types.tsx";
import BreakdownByCityTable from "./BreakdownByCityTable.tsx";
import ClientSelect from "../../../../../components/Selects/ClientSelect/ClientSelect.tsx";
import ParsingResultsTooltip from "./ParsingResultsTooltip.tsx";

const ProductsPreview = () => {
    const { barcodeProductsMap, createDeals, form } = usePrefillDealsWithExcelContext();

    const getTitle = (barcode: string, productsData: ProductExcelData) => {
        if (productsData.products.length === 1) {
            return `Товар со штрихкодом ${barcode}`;
        }
        return `Товары со штрихкодом ${barcode}`;
    };

    const getProductsData = () => {
        return barcodeProductsMap.entries().map(([barcode, productsData]) => (
                <div key={barcode} className={styles["deal-container-wrapper"]}>
                    <Stack>
                        <Title order={5}>
                            {getTitle(barcode, productsData)}
                        </Title>
                        <Flex direction={"row"} gap={"md"} flex={10}>
                            <Box flex={7}>
                                <ProductsTable barcode={barcode} productsData={productsData} />
                            </Box>
                            <Box flex={3}>
                                <BreakdownByCityTable breakdowns={productsData.breakdowns} />
                            </Box>
                        </Flex>
                    </Stack>
                </div>
            ),
        ).toArray();
    };

    return (
        <Stack gap={"md"}>
            <Title order={3}>Предпросмотр</Title>
            <form onSubmit={form.onSubmit((values) => createDeals(values))}>
                <ClientSelect
                    {...form.getInputProps("client")}
                    inputContainer={(children) => (
                        <Group align={"flex-start"}>
                            {children}
                            <Group>
                                <Button
                                    variant="outline"
                                    type="submit"
                                >
                                    Создать сделки
                                </Button>
                                <ParsingResultsTooltip />
                            </Group>
                        </Group>
                    )}
                />
            </form>
            {getProductsData()}
        </Stack>
    );
};

export default ProductsPreview;