import { FC } from "react";
import { DropzoneProps, FileWithPath } from "@mantine/dropzone";
import ImageDropzone from "@/components/ui/ImageDropzone/ImageDropzone";
import { uploadProductImage } from "@/lib/client";
import { notifications } from "@/lib/notifications";
import BaseFormInputProps from "@/utils/baseFormInputProps";
import useImageDropzone from "./useImageDropzone";

interface RestProps {
    imageUrlInputProps?: BaseFormInputProps<string>;
    productId?: number;
    onUploaded?: () => void;
}

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

const ProductImageDropzone: FC<Props> = ({
    imageUrlInputProps,
    productId,
    onUploaded,
}: 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);

        uploadProductImage({
            path: {
                pk: productId,
            },
            body: {
                upload_file: file,
            },
        })
            .then(({ data }) => {
                notifications.success({ message: data?.message });
                setIsLoading(false);

                if (!data?.imageUrl) {
                    setShowDropzone(true);
                    return;
                }
                imageUrlInputProps?.onChange(data?.imageUrl);
                setShowDropzone(false);
                onUploaded && onUploaded();
            })
            .catch(err => {
                console.log(err);
                notifications.error({ message: err.toString() });
                setShowDropzone(true);
                setIsLoading(false);
            });
    };

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

export default ProductImageDropzone;
