import {Dropzone, DropzoneProps, FileWithPath} from "@mantine/dropzone";
import {FC, useState} from "react";
import {Button, Fieldset, Flex, Group, Image, Loader, rem, Text} from "@mantine/core";
import {IconPhoto, IconUpload, IconX} from "@tabler/icons-react";
import {omit} from "lodash";
import {BaseFormInputProps} from "../../types/utils.ts";
import {notifications} from "../../shared/lib/notifications.ts";
import {ProductService} from "../../client";

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


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

const ImageDropzone: FC<Props> = (props: Props) => {
    const [showDropzone, setShowDropzone] = useState(
        !(typeof props.imageUrlInputProps?.value === 'string' &&
            props.imageUrlInputProps.value.trim() !== '')
    );
    const [isLoading, setIsLoading] = useState(false);
    const restProps = omit(props, ['imageUrl', 'productId', 'imageUrlInputProps']);
    const onDrop = (files: FileWithPath[]) => {
        if (!props.productId || !props.imageUrlInputProps) return;
        if (files.length > 1) {
            notifications.error({message: "Прикрепите одно изображение"});
            return;
        }
        const file = files[0];
        // TODO check if file is image
        setIsLoading(true);
        ProductService.uploadProductImage({
            productId: props.productId,
            formData: {
                upload_file: file
            }
        }).then(({ok, message, imageUrl}) => {
            notifications.guess(ok, {message});
            setIsLoading(false);

            if (!ok || !imageUrl) {
                setShowDropzone(true);

                return;
            }
            props.imageUrlInputProps?.onChange(imageUrl);
            setShowDropzone(false);
        }).catch(error => {
            notifications.error({message: error.toString()});
            setShowDropzone(true);
            setIsLoading(false);
        });
    }
    const getBody = () => {
        return props.imageUrlInputProps?.value && !showDropzone ? (
            <Image src={props.imageUrlInputProps.value}/>
        ) : (

            <Dropzone
                {...restProps}
                accept={["image/png",
                    "image/jpeg",
                    "image/gif",
                    "image/bmp",
                    "image/tiff",
                    "image/x-icon",
                    "image/webp",
                    "image/svg+xml",
                    "image/heic"]}
                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>
                            Перенесите изображение или нажмите чтоб выбрать файл
                        </Text>

                    </div>
                </Group>
            </Dropzone>
        );
    }
    return (
        <Flex
            gap={rem(10)}
            direction={"column"}

        >
            <Fieldset
                legend={'Изображение'}>
                <Flex justify={"center"}>
                    {isLoading ? <Loader/> : getBody()}
                </Flex>
            </Fieldset>
            {!showDropzone &&
                <Button onClick={() => setShowDropzone(true)} variant={"default"}>Заменить изображение {}</Button>
            }
        </Flex>
    )
}

export default ImageDropzone;