// React Imports
import { useState } from 'react'

// MUI Imports
import Box from '@mui/material/Box'
import IconButton from '@mui/material/IconButton'
import Dialog from '@mui/material/Dialog'
import DialogContent from '@mui/material/DialogContent'

// Third-party Imports
import classnames from 'classnames'

type Props = {
  images: string[]
  onRemove?: (index: number) => void
  className?: string
  readOnly?: boolean
}

const ImagePreview = ({ images, onRemove, className, readOnly = false }: Props) => {
  // States
  const [openDialog, setOpenDialog] = useState(false)
  const [selectedImage, setSelectedImage] = useState<string>('')

  const handleImageClick = (image: string) => {
    setSelectedImage(image)
    setOpenDialog(true)
  }

  const handleCloseDialog = () => {
    setOpenDialog(false)
    setSelectedImage('')
  }

  if (images.length === 0) {
    return null
  }

  return (
    <>
      <Box className={classnames('flex flex-wrap gap-2', className)}>
        {images.map((image, index) => (
          <Box
            key={index}
            className='relative inline-block rounded overflow-hidden border border-divider'
            sx={{
              width: 80,
              height: 80,
              '& img': {
                width: '100%',
                height: '100%',
                objectFit: 'cover',
                cursor: 'pointer'
              }
            }}
          >
            <img src={image} alt={`Preview ${index + 1}`} onClick={() => handleImageClick(image)} />
            {!readOnly && onRemove && (
              <IconButton
                size='small'
                onClick={() => onRemove(index)}
                className='absolute top-0 right-0 bg-backgroundPaper opacity-80 hover:opacity-100'
                sx={{
                  width: 24,
                  height: 24,
                  '&:hover': {
                    backgroundColor: 'var(--mui-palette-error-main)',
                    color: 'var(--mui-palette-error-contrastText)'
                  }
                }}
              >
                <i className='tabler-x text-sm' />
              </IconButton>
            )}
          </Box>
        ))}
      </Box>

      <Dialog open={openDialog} onClose={handleCloseDialog} maxWidth='md' fullWidth>
        <DialogContent className='flex items-center justify-center p-6'>
          <img
            src={selectedImage}
            alt='Preview'
            style={{
              maxWidth: '100%',
              maxHeight: '80vh',
              objectFit: 'contain'
            }}
          />
        </DialogContent>
      </Dialog>
    </>
  )
}

export default ImagePreview

