import { FC } from "react";
import { IconPhoto, IconUpload, IconX } from "@tabler/icons-react";
import { Fieldset, Flex, Group, Loader, rem, Text } from "@mantine/core";
import { Dropzone, DropzoneProps, FileWithPath } from "@mantine/dropzone";
import InlineButton from "@/components/ui/InlineButton/InlineButton";
import { deleteProductBarcodeImage, uploadProductBarcodeImage } from "@/lib/client";
import { notifications } from "@/lib/notifications";
import useImageDropzone from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/components/ProductImageDropzone/useImageDropzone";
import BaseFormInputProps from "@/utils/baseFormInputProps";


// Barcode image aspects ratio should be equal 58/40
const BARCODE_IMAGE_RATIO = 1.45;

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

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

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

    const onDeleteBarcodeImage = () => {
        if (!productId || !imageUrlInputProps) return;
        const { setIsLoading } = imageDropzoneProps;
        setIsLoading(true);

        deleteProductBarcodeImage({
            path: {
                pk: productId,
            },
        })
            .then(({ data }) => {
                notifications.success({ message: data?.message });
                imageUrlInputProps.onChange("");
                setIsLoading(false);
                onUploaded && onUploaded();
            })
            .catch(err => {
                console.log(err);
                notifications.error({ message: err.toString() });
                setIsLoading(false);
            });
    };

    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);

        uploadProductBarcodeImage({
            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);
            });
    };

    const getBody = () => {
        return imageUrlInputProps?.value ? (
            // eslint-disable-next-line jsx-a11y/alt-text
            <object
                style={{
                    aspectRatio: BARCODE_IMAGE_RATIO,
                    width: "240px",
                }}
                data={imageUrlInputProps?.value}
            />
        ) : (
            <Dropzone
                accept={["application/pdf"]}
                multiple={false}
                onDrop={onDrop}>
                <Group
                    justify="center"
                    gap="xl"
                    style={{ pointerEvents: "none" }}>
                    <Dropzone.Accept>
                        <IconUpload
                            style={{
                                width: rem(52),
                                height: rem(52),
                                color: "var(--mantine-color-blue-6)",
                            }}
                            stroke={1.5}
                        />
                    </Dropzone.Accept>
                    <Dropzone.Reject>
                        <IconX
                            style={{
                                width: rem(52),
                                height: rem(52),
                                color: "var(--mantine-color-red-6)",
                            }}
                            stroke={1.5}
                        />
                    </Dropzone.Reject>
                    <Dropzone.Idle>
                        <IconPhoto
                            style={{
                                width: rem(52),
                                height: rem(52),
                                color: "var(--mantine-color-dimmed)",
                            }}
                            stroke={1.5}
                        />
                    </Dropzone.Idle>

                    <div style={{ textAlign: "center" }}>
                        <Text
                            size="xl"
                            inline>
                            Перенесите или нажмите чтоб выбрать файл <br />
                            Pdf-файл должен содержать 1 страницу размером 58 х
                            40
                        </Text>
                    </div>
                </Group>
            </Dropzone>
        );
    };

    return (
        <Flex
            gap={"xs"}
            direction={"column"}>
            <Fieldset legend={"Штрихкод"}>
                <Flex justify={"center"}>
                    {imageDropzoneProps.isLoading ? <Loader /> : getBody()}
                </Flex>
            </Fieldset>
            {imageUrlInputProps?.value && (
                <>
                    <InlineButton
                        onClick={() => imageUrlInputProps?.onChange("")}>
                        Заменить штрихкод
                    </InlineButton>
                    <InlineButton onClick={onDeleteBarcodeImage}>
                        Удалить штрихкод
                    </InlineButton>
                </>
            )}
        </Flex>
    );
};

export default BarcodeImageDropzone;
