import React, { useState } from "react";

import Box from "@mui/material/Box";
import ImageList from "@mui/material/ImageList";
import ImageListItem from "@mui/material/ImageListItem";
import ImageListItemBar from "@mui/material/ImageListItemBar";
import Modal from "@mui/material/Modal";

import { AssetList } from "../types/asset";
import { ArticleAsset } from "../types/contrib";

export interface ProductAssetsGalleryProps {
  assets: AssetList[] | ArticleAsset[];
}

export const ProductAssetsGallery: React.FC<ProductAssetsGalleryProps> = ({ assets }) => {
  const [selectedAsset, setSelectedAsset] = useState<AssetList | ArticleAsset | null>(null);
  const imageAssets = assets.filter((asset) => asset.asset_type == "image");

  return (
    <>
      <Modal
        aria-describedby="modal-modal-description"
        aria-labelledby="modal-modal-title"
        open={selectedAsset !== null}
        sx={() => ({
          cursor: "pointer",
        })}
        onClose={() => setSelectedAsset(null)}
      >
        <Box
          sx={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            width: "100vw", // Set explicit width
            height: "100vh", // Set explicit height
            bgcolor: "rgba(0, 0, 0, 0.7)", // Dark overlay background
            boxShadow: 24,
            p: 2, // Reduced padding
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            overflow: "hidden", // Hide any overflowing content
            outline: "none",
          }}
          onClick={() => setSelectedAsset(null)}
        >
          {selectedAsset !== null && (
            <img
              alt={selectedAsset.caption}
              loading="lazy"
              src={selectedAsset.url}
              style={{
                maxWidth: "100%",
                maxHeight: "100%",
                objectFit: "contain",
                borderRadius: "8px", // Subtle rounded corners for the image
              }}
            />
          )}
        </Box>
      </Modal>

      <ImageList cols={3} gap={8} variant="masonry">
        {imageAssets.map((asset) => (
          <ImageListItem key={asset.id} onClick={() => setSelectedAsset(asset)}>
            <img alt={asset.caption} loading="lazy" src={asset.url} />
            <ImageListItemBar subtitle={asset.caption} />
          </ImageListItem>
        ))}
      </ImageList>
    </>
  );
};
