import { makeStyles, Button, TextField, Typography } from '@material-ui/core'
import { useState } from 'react';
import { useDispatch } from 'react-redux';

import UploadAvatar from './UploadAvatar'
import { asyncCreateUser } from '../../../redux/authorization/operations'
import { format } from '../../../helpers'

const useStyles = makeStyles({
  container: {
    display: 'flex',
    alignItems: 'center',
    alignContent:'center',
    flexDirection: 'column',
    width: 350,
    margin: '0 auto',
    paddingTop: 64,
    paddingBottom: 24,
  },
  title: {
    marginBottom: 20,
    textAlign: 'center'
  },
  buttonNext: {
    marginTop: 20,
    height: 50,
    color: '#f8f8f8',
    backgroundColor:'#1d74c5',
  },
  textField: {
    marginBottom:20
  }
})

const Registration = () => {
  const classes = useStyles()
  const [name, setName] = useState<string>('')
  const [lastName, setLastName] = useState<string>('')
  const [upload, setUpload] = useState<any>(null)
  const dispatch = useDispatch()

  const isValidCredentials = () => {
    const validName = name.length
    const validLastName = lastName.length
    if (validName < 3 || validName > 30) return false
    if (validLastName < 3 || validLastName > 30) return false
    if(!upload) return false
    return true
  }

  const handleTextField = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = format(e.target.value)
    const name = e.target.name
    switch (name) {
      case 'name':
        setName(value)
        break;
      case 'lastName':
        setLastName(value)
        break;
      default:
        break;
    }
  }

  const handleUpdateUser = async() => dispatch(asyncCreateUser(name,lastName,upload))

  return (
    <div className={classes.container} >
      <Typography
        className={classes.title}
        variant="h5"
        color="initial">
        Please upload avatar and fill credentials*
      </Typography>      
      <UploadAvatar
        setUpload={setUpload}
      />
      <TextField
        id="name"
        name='name'
        label="Name"
        value={name}
        fullWidth
        variant='outlined'
        onChange={handleTextField}
        className={classes.textField}
        required
        />
      <TextField
        id="lastName"
        name='lastName'
        label="LastName"
        value={lastName}
        fullWidth
        variant='outlined'
        onChange={handleTextField}
        className={classes.textField}
        required
        />
      {isValidCredentials() &&
        <Button
        onClick={handleUpdateUser}
        className={classes.buttonNext}
        color='primary'
        variant="contained"
        fullWidth
        > NEXT
      </Button>}
    </div>
  );
};

export default Registration;