import { useEffect, useState } from 'react'
import { AppDispatch, AppState, useAppDispatch } from '../../store/store'
import { deletePhotoById, getPhotosByUserId, setTargetedUser } from '../../store/photos/photos.slice'
import { shallowEqual, useSelector } from 'react-redux'
import IPhoto from '../../interfaces/IPhoto'
import Backdrop from '@mui/material/Backdrop';
import Box from '@mui/material/Box';
import Modal from '@mui/material/Modal';
import Fade from '@mui/material/Fade';
import { useNavigate, useParams } from 'react-router-dom'
import { Button, CardMedia } from '@mui/material'
import image_not_found from '../../assets/image_not_found.png'
import PhotoUserGalleryBlock from '../../components/PhotoUserGalleryBlock/PhotoUserGalleryBlock'

const modalStyles = {
    position: 'absolute' as 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    maxWidth: 1000,
    width: '100%',
    bgcolor: 'background.paper',
    border: '2px solid #000',
    boxShadow: 24,
    p: 1,
    borderRadius: '5px'
};

export const UserGallery: React.FunctionComponent = (): React.ReactElement => {

    const [open, setOpen] = useState<boolean>(false);
    
    const [fullImageSrc, setFullImageSrc] = useState<string>('')

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

    const params = useParams()

    const dispatch: AppDispatch = useAppDispatch()

    const {photosByUser, targetedUser} = useSelector((state: AppState) => state.photos, shallowEqual)

    const {user, isAuth} = useSelector((state: AppState) => state.users, shallowEqual)

    const navigate = useNavigate()

    const showFullImageHandler = (src: string) => {
        setFullImageSrc(src)
        setOpen(true)
    }

    const deletePhotoHandler = (id: string) => {
        dispatch(deletePhotoById(id))
    }

    const goToAddForm = () => {
        navigate('/add-photo')
    }

    useEffect(() => {
        if (params.id) dispatch(getPhotosByUserId(params.id))
        if (params.id && params.id === user?._id) dispatch(setTargetedUser(user))
    }, [])

    return (
        <div
            style={{
                maxWidth: '1400px', 
                width: '100%', 
                margin: '0 auto'
            }}
        >
            <Modal
                aria-labelledby="transition-modal-title"
                aria-describedby="transition-modal-description"
                open={open}
                onClose={handleClose}
                closeAfterTransition
                slots={{ backdrop: Backdrop }}
                slotProps={{
                    backdrop: {
                        timeout: 500,
                    },
                }}
            >
                <Fade in={open}>
                <Box sx={modalStyles}>
                <CardMedia
                    component="img"
                    style={{
                        maxWidth: '100%',
                        height: 'auto',
                        maxHeight: '70vh'
                    }}
                    image={import.meta.env.VITE_BASE_URL + 'uploads/' + fullImageSrc}
                    alt="full image"
                    onError = {(e) => {
                        e.currentTarget.src = image_not_found
                    }}
                />
                </Box>
                </Fade>
            </Modal>
            <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
            <h1>{ isAuth && targetedUser._id === user?._id ? 'This is your gallery' : `${targetedUser.username}'s gallery`}</h1>
                {isAuth && targetedUser._id === user?._id ?   
                <Button variant="contained" size='medium' onClick={goToAddForm}>
                    Add Photo
                </Button> : null}
            </div>
            <div
                style={{                
                    display: 'flex',
                    justifyContent: 'space-between',
                    flexWrap: 'wrap'
                }}
            >
                {
                    photosByUser && photosByUser.length ?
                    photosByUser.map((photo: IPhoto) => {
                        return <PhotoUserGalleryBlock
                                    key={photo._id}
                                    photo={photo}
                                    showFullImage={()=>showFullImageHandler(photo.photo)}
                                    deletePhoto={()=>{deletePhotoHandler(photo._id)}}
                                />
                        
                    }): <h1>Gallery is empty</h1>
                }
            </div>
        </div>
    )
}

export default UserGallery