import { createContext, FC, useContext, useState } from "react";
import { useDisclosure } from "@mantine/hooks";
import { DealsWithExcelForm, ProductExcelData } from "../drawers/PrefillDealWithExcelDrawer/types.tsx";
import { FileWithPath } from "@mantine/dropzone";
import { notifications } from "../../../shared/lib/notifications.ts";
import { DealService, type ProductFromExcelSchema, ProductSchema } from "../../../client";
import UseExcelDropzone from "../../../types/UseExcelDropzone.tsx";
import { useForm, UseFormReturnType } from "@mantine/form";
import { useDealPageContext } from "./DealPageContext.tsx";

type PrefillDealsWithExcelContextState = {
    prefillWithExcelOpened: boolean;
    prefillWithExcelOnClose: () => void;
    prefillWithExcelOnOpen: () => void;
    barcodeProductsMap: Map<string, ProductExcelData>,
    onProductSelectChange: (barcode: string, selectedProduct: ProductSchema) => void,
    onDrop: (files: FileWithPath[]) => void;
    excelDropzone: UseExcelDropzone;
    createDeals: (values: DealsWithExcelForm) => void;
    form: UseFormReturnType<DealsWithExcelForm>;
    errors: string[];
};

const PrefillDealsWithExcelContext = createContext<PrefillDealsWithExcelContextState | undefined>(
    undefined,
);
const usePrefillDealsWithExcelContextState = () => {
    const [prefillWithExcelOpened, { open, close }] = useDisclosure(false);
    const { refetchDeals } = useDealPageContext();
    const [isLoading, setIsLoading] = useState(false);
    const [errors, setErrors] = useState<string[]>([]);
    const excelDropzone: UseExcelDropzone = {
        isLoading,
        setIsLoading,
    };

    const form = useForm<DealsWithExcelForm>({
        validate: {
            client: client => !client && "Выберите клиента",
        },
    });

    const [barcodeProductsMap, setBarcodeProductsMap] = useState<Map<string, ProductExcelData>>(new Map());

    const onDrop = (files: FileWithPath[]) => {
        if (files.length > 1) {
            notifications.error({ message: "Прикрепите одно изображение" });
            return;
        }
        const file = files[0];

        setIsLoading(true);
        DealService.parseDealsExcel({
            formData: {
                upload_file: file,
            },
        })
            .then(res => {
                const barcodeProductsMap = new Map();
                res.rows.forEach((row) => {
                    const productsData: ProductExcelData = row;
                    productsData.selectedProduct = productsData.products[0];
                    barcodeProductsMap.set(row.barcode, row);
                });
                setBarcodeProductsMap(barcodeProductsMap);
                setErrors(res.errors);
            })
            .catch(error => {
                notifications.error({ message: error.toString() });
            })
            .finally(() => setIsLoading(false));
    };

    const onProductSelectChange = (barcode: string, selectedProduct: ProductSchema) => {
        const newBarcodeProductsMap = new Map(barcodeProductsMap);
        const productsData = newBarcodeProductsMap.get(barcode);
        if (!productsData) return;
        productsData.selectedProduct = selectedProduct;

        newBarcodeProductsMap.set(
            barcode,
            productsData,
        );
        setBarcodeProductsMap(newBarcodeProductsMap);
    };

    const prefillWithExcelOnClose = () => {
        close();
        setBarcodeProductsMap(new Map());
        form.reset();
    };

    const createDeals = (values: DealsWithExcelForm) => {
        const products: ProductFromExcelSchema[] = barcodeProductsMap.entries().map(([, productData]) => {
            return {
                productId: productData.selectedProduct!.id,
                citiesBreakdown: productData.breakdowns,
            };
        }).toArray();

        DealService.createDealsExcel({
            requestBody: {
                products,
                clientId: values.client?.id ?? -1,
            },
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                if (ok) prefillWithExcelOnClose();
                refetchDeals();
            })
            .catch(err => console.log(err));
    };

    return {
        prefillWithExcelOpened,
        prefillWithExcelOnClose,
        prefillWithExcelOnOpen: open,
        barcodeProductsMap,
        onProductSelectChange,
        onDrop,
        excelDropzone,
        createDeals,
        form,
        errors,
    };
};

type PrefillDealsWithExcelContextProviderProps = {
    children: React.ReactNode;
};

export const PrefillDealsWithExcelContextProvider: FC<PrefillDealsWithExcelContextProviderProps> = ({ children }) => {
    const state = usePrefillDealsWithExcelContextState();
    return (
        <PrefillDealsWithExcelContext.Provider value={state}>
            {children}
        </PrefillDealsWithExcelContext.Provider>
    );
};

export const usePrefillDealsWithExcelContext = () => {
    const context = useContext(PrefillDealsWithExcelContext);
    if (!context) {
        throw new Error(
            "usePrefillDealsWithExcelContext must be used within a PrefillDealsWithExcelContextProvider",
        );
    }
    return context;
};
