import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import {
  Box,
  Typography,
  IconButton,
  Dialog,
  DialogContent,
} from "@mui/material";
import Grid from '@mui/material/Grid2';
import CloseIcon from "@mui/icons-material/Close";
import ZoomInIcon from '@mui/icons-material/ZoomIn';
import ZoomOutIcon from '@mui/icons-material/ZoomOut';
import defaultImage from "../../assets/images/default.png";
import { Carousel } from 'react-responsive-carousel';

// Utility function to check if an object is empty
const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;

const ImageView = () => {

  const product = useSelector((state) => state.products.product.data)

  const [previewImage, setPreviewImage] = useState("");
  const [isZoomed, setIsZoomed] = useState(false);
  const [zoomSize, setZoomSize] = useState(100)
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {

    if (!isEmptyObject(product)) {
      setPreviewImage(product?.images[0]?.url)
    }

  }, [product])

  const handleThumbnailClick = (image) => {
    setPreviewImage(image);
  };

  const handleZoomToggle = () => {
    setIsZoomed(!isZoomed);
  };

  const handleSlideChange = (index) => {
    setPreviewImage(product?.images[index]?.url)
  };

  const onZoomIn = () => {
    if (zoomSize > 310) return
    setZoomSize(zoomSize + 20)
  }

  const onZoomOut = () => {
    if (zoomSize < 40) return
    setZoomSize(zoomSize - 20)
  }


  return (
    <Box sx={{ flexGrow: 1 }}>
      <Grid container spacing={2}>
        {/* Image Preview Section */}
        <Grid item size={12}>
          <Box
            sx={{
              overflow: "hidden",
              cursor: "pointer",
              px: {
                xs: 0,
                sm: 0,
                md: 15
              }
            }}
          >

            <Carousel
              showStatus={false}
              showIndicators={false}
              onClickItem={() => {
                handleZoomToggle()
                setZoomSize(100)
              }}
              onChange={(index) => handleSlideChange(index)}
              selectedItem={currentIndex}>
              {product?.images?.map(({ src, url }, index) => (
                <Box
                  key={index}
                  component="img"
                  src={url}
                  alt={`img_${index + 1}`}
                  sx={{
                    width: "100%",
                    zIndex: 0,
                    position: "relative",
                    top: "50%",
                    transform: "translateY(-50%)"
                  }}
                />
              ))}
            </Carousel>

          </Box>
        </Grid>

        {/* Image Control Section */}
        <Grid item size={12}>
          <Box
            sx={{
              display: "flex",
              flexDirection: "row",
              justifyContent: {
                xs: "left",
                sm: "left",
                md: "center"
              },
              overflowX: "scroll",
              overflowY: "none",
              padding: 2,
              gap: 2
            }}
          >
            {product?.images?.map(({ src, url }, index) => (
              <IconButton
                key={index}
                onClick={() => {
                  handleThumbnailClick(url)
                  setCurrentIndex(index)
                }}
                sx={{
                  p: 0.4,
                  borderRadius: 1,
                  backgroundColor: (previewImage == url) ? "#95AAC5" : "none"
                }}
              >
                <img
                  src={url}
                  alt={`img_${index + 1}`}
                  style={{
                    width: "100%",
                    height: "auto",
                    maxWidth: "75px",
                  }}
                />
              </IconButton>
            ))}
          </Box>
        </Grid>

      </Grid>

      {/* Zoom Dialog */}
      <Dialog fullScreen open={isZoomed} onClose={handleZoomToggle} maxWidth="lg">
        <DialogContent
          sx={{
            position: "relative",
            overflow: "hidden", // Prevent scrolling on DialogContent
            height: "90vh", // Adjust height as needed
            p: 0
          }}
        >
          {/* Fixed position close button */}
          <Box
            sx={{
              width: 50,
              height: 50,
              position: "absolute",
              top: 10,
              right: {
                xs: 1.5,
                sm: 1.5,
                md: 10
              },
              zIndex: 2, // Ensure it stays above other content
            }}
          >
            <IconButton
              onClick={handleZoomToggle}
              sx={{
                backgroundColor: "white",
                color: "black",
                "&:hover": {
                  backgroundColor: "lightgray",
                },
              }}
            >
              <CloseIcon />
            </IconButton>
            <IconButton
              onClick={onZoomIn}
              sx={{
                backgroundColor: "white",
                color: "black",
                mt: 1,
                "&:hover": {
                  backgroundColor: "lightgray",
                },
              }}
            >
              <ZoomInIcon />
            </IconButton>
            <IconButton
              onClick={onZoomOut}
              sx={{
                backgroundColor: "white",
                color: "black",
                mt: 1,
                "&:hover": {
                  backgroundColor: "lightgray",
                },
              }}
            >
              <ZoomOutIcon />
            </IconButton>
          </Box>

          {/* Scrollable content */}
          <Box
            sx={{
              overflow: "auto", // Allow scrolling within this Box
              height: "100%", // Fill available height of DialogContent
              display: "flex"
            }}
          >
            <img
              src={previewImage || defaultImage}
              alt="Zoomed Preview"
              style={{
                width: `${zoomSize}%`,
                margin: "auto auto",
                height: "auto",
              }}
            />
          </Box>
        </DialogContent>
      </Dialog>

    </Box>
  );
};

export default ImageView;
