import { shallowEqual } from "react-redux"
import { Alert, Collapse, IconButton, TextField } from '@mui/material';
import { AppDispatch, AppState, useAppDispatch } from "../../store/store"
import { useSelector } from "react-redux"
import Preloader from "../../components/UI/Preloader/Preloader"
import { ChangeEvent, FormEvent, useState } from "react"
import IPhotoDto from "../../interfaces/IPhotoDto"
import { addPhoto } from "../../store/photos/photos.slice"
import Box from '@mui/material/Box';
import CloseIcon from '@mui/icons-material/Close';

import styles from './AddForm.module.css'

const AddForm: React.FunctionComponent = (): React.ReactElement => {

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

    const [fileName, setFileName] = useState<string>('')

    const [photoDto, setPhotoDto] = useState<IPhotoDto>({
        title: '',
        photo: undefined
    })

    const [titleError, setTitleError] = useState<boolean>(false);

    const [photoError, setPhotoError] = useState<boolean>(false);

    const dispatch: AppDispatch = useAppDispatch()

    const inputHandler = (e: ChangeEvent<HTMLInputElement>): void => {
        setPhotoDto(prevState => {
            return {...prevState, [e.target.name]: e.target.value}
        })
    }

    const inputFileHandler = (e: ChangeEvent<HTMLInputElement>): void => {
        setPhotoDto(prevState => {
            return {...prevState, 
                photo: e.target.files ? e.target.files[0] : undefined}
        })
        setFileName(e.target.files && e.target.files[0] ? e.target.files[0].name : '')
    }

    const submitHandler = (e: FormEvent): void => {
        e.preventDefault()
        if (photoDto.title.trim() === ''){
            setTitleError(true)
        }
        if (!photoDto.photo){
            setPhotoError(true)
        }
        if (photoDto.title.trim() === '' || !photoDto.photo){
            return
        }
        const formData = new FormData()
        Object.keys(photoDto).forEach((key: string) => {
            //@ts-ignore
            formData.append(key, photoDto[key])
        })
        dispatch(addPhoto(formData))
        setPhotoDto({
            title: '',
            photo: undefined
        })
        setTitleError(false)
        setPhotoError(false)
        setFileName('')
    }
    
    return(
        <div
        >
            {
                loadingPhotos ? <Preloader/> : null
            }
            <h1>Add new photo</h1>
            <form
                onSubmit={submitHandler}
                style={{margin: '10px', padding: '20px', background: '#e0e0e0', borderRadius: '5px', display: 'flex', flexDirection: 'column'}}
            >
            <Box sx={{ width: '100%' }}>
            <Collapse in={titleError}>
                <Alert
                action={
                    <IconButton
                    aria-label="close"
                    color="inherit"
                    size="small"
                    onClick={() => {
                        setTitleError(false);
                    }}
                    >
                    <CloseIcon fontSize="inherit" />
                    </IconButton>
                }
                sx={{ mb: 2 }}
                severity="error"
                >
                Title should exist!
                </Alert>
            </Collapse>
            </Box>
            <TextField 
                id="outlined-basic" 
                label="Photo title" 
                variant="outlined" 
                style={{marginBottom: '20px'}}
                value={photoDto.title}
                name='title'
                onChange={inputHandler}
                autoComplete='off'
            />
            <Box sx={{ width: '100%' }}>
            <Collapse in={photoError}>
                <Alert
                action={
                    <IconButton
                    aria-label="close"
                    color="inherit"
                    size="small"
                    onClick={() => {
                        setPhotoError(false);
                    }}
                    >
                    <CloseIcon fontSize="inherit" />
                    </IconButton>
                }
                sx={{ mb: 2 }}
                severity="error"
                >
                Photo should exist!
                </Alert>
            </Collapse>
            </Box>
            <label style={{height: 'auto', margin: '10px', maxWidth: '30%', display: 'flex', flexDirection: 'column'}}>
                <input
                    style={{display: "none"}}
                    name={'photo'}
                    type="file"
                    placeholder="Image"
                    accept=".png, .jpg, .jpeg"
                    onChange={inputFileHandler}
                />
                <h1 className={styles.file_input} style={{margin: '0'}}>
                    Choose file
                </h1>
                <span className={styles.filename}>{fileName}</span>
            </label>
            <button className={styles.add_btn}>SEND</button>
            </form>
        </div>
    )
}

export default AddForm