import { FormEvent, useEffect, useState } from 'react'
import styles from './AuthorizeForm.module.css'
import IUserCreateDto from '../../interfaces/IUserCreateDto'
import { AppDispatch, AppState, useAppDispatch } from '../../store/store'
import { useLocation, useNavigate } from 'react-router-dom'
import { shallowEqual, useSelector } from 'react-redux'
import Preloader from '../../components/UI/Preloader/Preloader'
import { createUser, hideMessage, loginUser } from '../../store/user/user.slice'
import Alert from '@mui/material/Alert';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import { FormControl, FormControlLabel, IconButton, InputAdornment, InputLabel, OutlinedInput, Switch, TextField } from '@mui/material'

const AuthorizeForm: React.FunctionComponent = (): React.ReactElement => {
    const navigate = useNavigate()

    const dispatch: AppDispatch = useAppDispatch()
    const { isAuth, messageUser, loadingUser } = useSelector((state: AppState) => state.users, shallowEqual)
    const location = useLocation()
    const [userValues, setUserValues] = useState<IUserCreateDto>({
        username: '',
        password: ''
    })

    const [buttonDisabled, setButtonDisabled] = useState<boolean>(true)

    const [addNewUser, setAddNewUser] = useState<boolean>(true)

    const [showPassword, setShowPassword] = useState<boolean>(false);

    const handleClickShowPassword = () => setShowPassword((show) => !show);

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

    const toggleChangeHandler = () => {
        setAddNewUser(!addNewUser)
    }

    const submitHandler = async (e: FormEvent) => {
        e.preventDefault()
        if (addNewUser){
            await dispatch(createUser(userValues))
        } else{
            await dispatch(loginUser(userValues))
        }
    }

    const handleMouseDownPassword = (event: React.MouseEvent<HTMLButtonElement>) => {
        event.preventDefault();
    };

    useEffect(() => {
        checkButton()
    },[userValues])

    useEffect(() => {
        if (isAuth){
            navigate(location.state?.from ? location.state.from : '/')
        }
    }, [isAuth])

    const checkButton = () => {
        if (userValues.username.trim() === '' || userValues.password.trim() === ''){
            setButtonDisabled(true)
        } else{
            setButtonDisabled(false)
        }
    }

    useEffect(() => {
        dispatch(hideMessage())
    }, [])

    return (
        <div className={styles.AuthorizeForm}>
            {
                loadingUser ? <Preloader/> : null
            }
            <form onSubmit={submitHandler}>
                {
                    messageUser.trim() !== '' ?
                    <Alert variant="filled" severity="error">
                        {messageUser}
                    </Alert> : null
                }
                <p>{addNewUser ? 'Register user' : 'Log in user'}</p>

                <FormControl sx={{ m: 1, width: '80%' }} variant="outlined">
                <InputLabel htmlFor="outlined-adornment-password">Username</InputLabel>
                    <OutlinedInput
                        id="outlined-adornment-password"
                        type={'text'}
                        label="Username"
                        name={'username'}
                        autoComplete='off'
                        value={userValues.username}
                        onChange={inputHandler}
                        style={{
                            marginBottom: '10px',
                            width: '100%'
                        }
                    }    
                />
                </FormControl>
                
                <FormControl sx={{ m: 1, width: '80%' }} variant="outlined">
                <InputLabel htmlFor="outlined-adornment-password">Password</InputLabel>
                    <OutlinedInput
                        id="outlined-adornment-password"
                        type={showPassword ? 'text' : 'password'}
                        label="Password"
                        name={'password'}
                        autoComplete='off'
                        value={userValues.password}
                        onChange={inputHandler}
                        style={{
                            marginBottom: '10px',
                            width: '100%'
                        }}
                        endAdornment={
                        <InputAdornment position="end">
                            <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                            >
                            {showPassword ? <VisibilityOff /> : <Visibility />}
                            </IconButton>
                        </InputAdornment>
                        }
                />
                </FormControl>
                <FormControlLabel
                    control={<Switch
                        checked={addNewUser}
                        onChange={toggleChangeHandler}
                        inputProps={{ 'aria-label': 'controlled' }}
                    />} 
                    label={<p style={{color: 'black'}}>Add new user</p>}
                />
                <button
                    className={styles.login_btn}
                    disabled={buttonDisabled}
                >{addNewUser ? 'Register' : 'Log in'}</button>
            </form>
        </div>
    )
}

export default AuthorizeForm
