import React, { useState } from "react";
import { Box, IconButton, Modal, Tooltip, Button } from "@mui/material";
import { motion } from "framer-motion";
import DownloadIcon from "@mui/icons-material/Download";
import CloseIcon from "@mui/icons-material/Close";
import RotateRightIcon from "@mui/icons-material/RotateRight";

const imageExtensions = [
  ".jpg",
  ".jpeg",
  ".png",
  ".gif",
  ".bmp",
  ".webp",
  ".svg",
];

const ShowImage = ({ src, size }) => {
  const [open, setOpen] = useState(false);
  const [rotation, setRotation] = useState(0);

  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  const handleDownload = () => {
    if (!src || typeof src !== "string") return;
    try {
      const link = document.createElement("a");
      link.href = src;
      const filename = src.split("/").pop() || "document";
      link.download = filename;
      link.click();
    } catch (error) {
      console.error("Error downloading file:", error);
    }
  };

  const handleRotate = () => {
    setRotation((prevRotation) => prevRotation + 90);
  };

  const getFileExtension = () => {
    if (!src || typeof src !== "string") return "";
    try {
      const filename = src.split("/").pop();
      if (!filename || typeof filename !== "string") return "";
      const lastDotIndex = filename.lastIndexOf(".");
      if (lastDotIndex === -1) return "";
      return filename.substring(lastDotIndex + 1).toLowerCase();
    } catch (error) {
      console.error("Error getting file extension:", error);
      return "";
    }
  };

  const isImage = () => {
    if (!src || typeof src !== "string") return false;
    const extension = getFileExtension();
    return imageExtensions.includes(`.${extension}`);
  };

  if (!src || typeof src !== "string") {
    return "-";
  }

  if (!isImage()) {
    const fileExtension = getFileExtension();
    const buttonText = fileExtension
      ? `دانلود سند ${fileExtension}`
      : "دانلود سند";

    return (
      <Button
        size="small"
        variant="contained"
        startIcon={<DownloadIcon />}
        onClick={handleDownload}
        sx={{
          textTransform: "none",
          fontSize: "0.8rem",
          padding: "5px 10px",
        }}
      >
        {buttonText}
      </Button>
    );
  }

  return (
    <div>
      <Box
        component="img"
        src={src}
        alt="thumbnail"
        sx={{
          width: size ? size : "50px",
          height: size ? size : "50px",
          cursor: "pointer",
          borderRadius: "10px",
        }}
        onClick={handleOpen}
      />

      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
        sx={{ display: "flex", alignItems: "center", justifyContent: "center" }}
      >
        <motion.div
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          exit={{ scale: 0 }}
          transition={{ duration: 0.3 }}
          style={{ position: "relative" }}
        >
          <Box
            component="img"
            src={src}
            alt="full-size"
            sx={{
              maxWidth: "90vw",
              maxHeight: "90vh",
              minWidth: "40vw",
              minHeight: "40vh",
              borderRadius: "10px",
              transform: `rotate(${rotation}deg)`,
              transition: "transform 0.3s",
            }}
          />

          <Tooltip title="جهت دانلود تصویر کلید کنید" placement="right">
            <IconButton
              color="primary"
              onClick={handleDownload}
              sx={{
                position: "absolute",
                top: 16,
                right: 16,
                backgroundColor: "rgba(255, 255, 255, 0.7)",
                "&:hover": {
                  backgroundColor: "rgba(255, 255, 255, 1)",
                },
                boxShadow: "0 2px 10px rgba(0, 0, 0, 0.2)",
                borderRadius: "50%",
              }}
            >
              <DownloadIcon />
            </IconButton>
          </Tooltip>

          <Tooltip title="چرخش تصویر" placement="right">
            <IconButton
              color="default"
              onClick={handleRotate}
              sx={{
                position: "absolute",
                bottom: 16,
                right: 16,
                backgroundColor: "rgba(255, 255, 255, 0.7)",
                "&:hover": {
                  backgroundColor: "rgba(255, 255, 255, 1)",
                },
                boxShadow: "0 2px 10px rgba(0, 0, 0, 0.2)",
                borderRadius: "50%",
              }}
            >
              <RotateRightIcon />
            </IconButton>
          </Tooltip>

          <IconButton
            color="secondary"
            onClick={handleClose}
            sx={{
              position: "absolute",
              top: 16,
              left: 16,
              backgroundColor: "rgba(255, 255, 255, 0.7)",
              "&:hover": {
                backgroundColor: "rgba(255, 255, 255, 1)",
              },
              boxShadow: "0 2px 10px rgba(0, 0, 0, 0.2)",
              borderRadius: "50%",
            }}
          >
            <CloseIcon />
          </IconButton>
        </motion.div>
      </Modal>
    </div>
  );
};

export default ShowImage;
