import UploadIcon from "@icons/UploadIcon";
import DeleteIcon from '@mui/icons-material/Delete';
import {
    Box,
    ButtonBase,
    IconButton,
    SxProps,
    Theme,
    Typography,
    useTheme,
} from "@mui/material";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { CropModal, useCropModalState } from "@ui_kit/Modal/CropModal";
import { enqueueSnackbar } from "notistack";
import { useState } from "react";
import { UploadImageModal } from "../../pages/Questions/UploadImage/UploadImageModal";
import { useDisclosure } from "../../utils/useDisclosure";


const allowedFileTypes = ["image/png", "image/jpeg", "image/gif"];

interface Props {
    text?: string;
    sx?: SxProps<Theme>;
    heightImg: string;
    widthImg?: string;
    imageUrl: string | null;
    originalImageUrl: string | null;
    onImageUploadClick: (image: Blob) => void;
    onImageSaveClick: (image: Blob) => void;
    onDeleteClick: () => void;
}

//Научи функцию принимать данные для валидации
export const DropZone = ({ text, sx, heightImg, widthImg, imageUrl, originalImageUrl, onImageUploadClick, onImageSaveClick, onDeleteClick }: Props) => {
    const theme = useTheme();
    const quiz = useCurrentQuiz();
    const [isDropReady, setIsDropReady] = useState<boolean>(false);
    const [isImageUploadOpen, openImageUploadModal, closeImageUploadModal] = useDisclosure();
    const {
        isCropModalOpen,
        openCropModal,
        closeCropModal,
        imageBlob,
        setCropModalImageBlob,
    } = useCropModalState();

    if (!quiz) return null; // TODO throw and catch with error boundary 

    async function handleImageUpload(file: File) {
        if (file.size > 5 * 2 ** 20) return enqueueSnackbar("Размер картинки слишком велик");
        if (!allowedFileTypes.includes(file.type)) return enqueueSnackbar("Допустимые форматы изображений: png, jpeg, gif");

        onImageUploadClick?.(file);
        closeImageUploadModal();
        openCropModal(file);
    }

    const onDrop = (event: React.DragEvent<HTMLDivElement>) => {
        event.preventDefault();
        setIsDropReady(false);

        const file = event.dataTransfer.files[0];
        if (!file || imageUrl) return;

        handleImageUpload(file);
    };

    return (
        <Box
            onDragEnter={() => !imageUrl && setIsDropReady(true)}
            onDragExit={() => setIsDropReady(false)}
            onDragOver={e => e.preventDefault()}
            onDrop={onDrop}
            sx={{
                position: "relative",
                width: "100%",
                height: "120px",
                backgroundColor: theme.palette.background.default,
                border: `1px solid ${isDropReady ? "red" : theme.palette.grey2.main}`,
                borderRadius: "8px",
                ...sx,
            }}>
            <UploadImageModal
                isOpen={isImageUploadOpen}
                onClose={closeImageUploadModal}
                handleImageChange={handleImageUpload}
            />
            <CropModal
                isOpen={isCropModalOpen}
                imageBlob={imageBlob}
                originalImageUrl={originalImageUrl}
                setCropModalImageBlob={setCropModalImageBlob}
                onClose={closeCropModal}
                onSaveImageClick={onImageSaveClick}
            />
            <ButtonBase
                onClick={imageUrl ? () => openCropModal(imageUrl) : openImageUploadModal}
                sx={{
                    width: "100%",
                    height: "100%",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    borderRadius: "8px",
                }}
            >
                {imageUrl ?
                    <img
                        height={heightImg}
                        width={widthImg}
                        src={imageUrl}
                        style={{
                            objectFit: "scale-down",
                        }}
                    />
                    :
                    <>
                        <UploadIcon />
                        <Typography
                            sx={{
                                position: "absolute",
                                right: "10px",
                                bottom: "10px",
                                color: theme.palette.orange.main,
                                fontSize: "16px",
                                lineHeight: "19px",
                                textDecoration: "underline",
                            }}
                        >
                            {text}
                        </Typography>
                    </>
                }
            </ButtonBase>
            {imageUrl &&
                <IconButton
                    onClick={onDeleteClick}
                    sx={{
                        position: "absolute",
                        right: 0,
                        top: 0,
                        color: theme.palette.orange.main,
                        borderRadius: "8px",
                        borderBottomRightRadius: 0,
                        borderTopLeftRadius: 0,
                    }}
                >
                    <DeleteIcon />
                </IconButton>
            }
        </Box>
    );
};
