import { DropzoneProps, FileWithPath } from "@mantine/dropzone";
import { FC } from "react";
import { notifications } from "../../../../shared/lib/notifications.ts";
import { ProductService } from "../../../../client";
import { BaseFormInputProps } from "../../../../types/utils.ts";
import useImageDropzone from "../../../../hooks/useImageDropzone.tsx";
import ImageDropzone from "../../../../components/ImageDropzone/ImageDropzone.tsx";

interface RestProps {
    imageUrlInputProps?: BaseFormInputProps<string>;
    productId?: number;
}

type Props = Omit<DropzoneProps, "onDrop"> & RestProps;

const ProductImageDropzone: FC<Props> = ({ imageUrlInputProps, productId }: Props) => {
    const imageDropzoneProps = useImageDropzone({
        imageUrlInputProps,
    });

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

        setIsLoading(true);
        ProductService.uploadProductImage({
            productId,
            formData: {
                upload_file: file,
            },
        })
            .then(({ ok, message, imageUrl }) => {
                notifications.guess(ok, { message });
                setIsLoading(false);

                if (!ok || !imageUrl) {
                    setShowDropzone(true);
                    return;
                }
                imageUrlInputProps?.onChange(imageUrl);
                setShowDropzone(false);
            })
            .catch(error => {
                notifications.error({ message: error.toString() });
                setShowDropzone(true);
                setIsLoading(false);
            });
    };

    return (
        <ImageDropzone onDrop={onDrop} imageDropzone={imageDropzoneProps} />
    );
};

export default ProductImageDropzone;
