import styles from "../PrefillCardsWithExcelDrawer.module.css";
import ProductsTable from "./ProductsTable.tsx";
import { usePrefillCardsWithExcelContext } 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";
import { StatusSchema } from "../../../../../client";

type Props = {
    status: StatusSchema;
}

const ProductsPreview = ({ status }: Props) => {
    const { barcodeProductsMap, createCards, form } = usePrefillCardsWithExcelContext();

    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["card-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) => createCards(values, status))}>
                <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;