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


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

interface Props {
  text?: string;
  sx?: SxProps<Theme>;
  deleteIconSx?: SxProps<Theme>;
  imageUrl: string | null;
  originalImageUrl: string | null;
  onImageUploadClick: (image: Blob) => void;
  onImageSavedClick?: () => void;
  onDeleteClick: () => void;
  cropAspectRatio?: {
    width: number;
    height: number;
  };
}

//Научи функцию принимать данные для валидации
export const DropZone = ({
  text,
  sx,
  deleteIconSx,
  imageUrl,
  originalImageUrl,
  onImageUploadClick,
  onImageSavedClick,
  onDeleteClick,
  cropAspectRatio,
}: Props) => {
  const theme = useTheme();
  const quiz = useCurrentQuiz();

  const [isDropReady, setIsDropReady] = useState<boolean>(false);
  const [isImageUploadOpen, openImageUploadModal, closeImageUploadModal] = useDisclosure();

  if (!quiz) return null;

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

  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}
      />
      <ButtonBase
        onClick={ () => onImageSavedClick &&imageUrl ? onImageSavedClick() : openImageUploadModal()
        }
        sx={{
          width: "100%",
          height: "100%",
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          borderRadius: "8px",
          overflow: "hidden",
        }}
      >
        {imageUrl ? (
          <img
            src={imageUrl}
            style={{
              width: "100%",
              height: "100%",
              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,
              ...deleteIconSx,
            }}
          >
            <DeleteIcon />
          </IconButton>
        )}
    </Box>
  );
};
