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

import PhotoCameraFrontIcon from '@mui/icons-material/PhotoCameraFront';
import UploadAvatar from './UploadAvatar'
import FolderIcon from '@mui/icons-material/Folder';
import Webcam from "react-webcam";
import CameraIcon from '@mui/icons-material/Camera';
import { asyncCreateUser } from '../../../redux/authorization/operations'
import { format,playNotification,prodBaseURL } 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'
  },
  selfieWrapper: {
    marginBottom: 20,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    alignContent: 'center',
  },
  buttonNext: {
    marginTop: 20,
    height: 50,
    color: '#f8f8f8',
    backgroundColor:'#1d74c5',
  },
  textField: {
    marginBottom:20
  },
  overlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    width: '100vw',
    height: '100vh',
    zIndex: 100,
    backgroundColor: 'rgba(104, 105, 104, 0.6)',
    overflowY: 'hidden',
    display: 'flex',
    justifyContent: 'center',
    alignContent: 'center',
    alignItems: 'center',
    flexDirection:'column'
  },
  capturedPicture: {
    borderRadius: 10,
    border:'solid 2px rgb(62, 149, 231)'
  },  
  capturePhoto: {
    color: '#ffffff',
    cursor: 'pointer',
    '&:hover': {
      color: '#48ff00',
      animation: `$rotating 2s linear infinite`
    },
  },  
  '@keyframes rotating': {
	  'from': { transform: 'rotate(0deg)'},
	  'to': { transform: 'rotate(360deg)'},
   },  
})

const Registration = () => {
  const classes = useStyles()
  const [name, setName] = useState<string>('')
  const [lastName, setLastName] = useState<string>('')
  const [upload, setUpload] = useState<any>(null)
  const [selfie, setSelfie] = useState<any>(null)
  const [camera, setCamera] = useState<boolean>(false)
  const dispatch = useDispatch()
  const videoConstraints = {
    width: 1280,
    height: 720,
    facingMode: "user"
  };

  const isValidCredentials = () => {
    const validName = name.length
    const validLastName = lastName.length
    if (validName < 3 || validName > 30) return false
    if (validLastName < 3 || validLastName > 30) 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 handleOpenCamera = () => {
    setCamera(true)
    upload&&setUpload(null)
  }

  const handleCloseCamera = (e: any) => {
    const id = e.target.id
    if (id === 'overlay') setCamera(false)
  }  

  const handleUpdateUser = async () => {
    if (upload) {
      dispatch(asyncCreateUser(name, lastName, upload))
    }
    if (selfie) {
      fetch(selfie)
       .then(res => res.blob())
        .then(blob => {
          const imgFile = new File([blob], "selfie", { type: "image/jpeg" })
          dispatch(asyncCreateUser(name, lastName, imgFile))
      })
    }
  }

  return (
    <div className={classes.container} >
      <div className={classes.selfieWrapper}>
        <Typography variant="h6" color="initial"
          style={{ textAlign: "center", marginRight: 10 }}>
          Capture avatar
        </Typography>
        <PhotoCameraFrontIcon onClick={handleOpenCamera} fontSize='large'
          sx={{color: selfie ? 'rgb(62, 149, 231)' :
          '#6b6b6b',
          '&:hover': { color: 'rgb(41, 139, 231)' },cursor:'pointer'}}/>
      </div>      
      <UploadAvatar setUpload={setUpload} upload={upload} setSelfie={setSelfie} />
      <aside>
        <ul>
          {upload || selfie?
            <ListItem>
              <ListItemIcon>
                <FolderIcon/>
              </ListItemIcon>
              <ListItemText primary="Avatar uploaded"
              secondary={`${upload?upload.path:'selfie.jpeg'} -${upload?upload.size:(selfie.length*(3/4))-2} bytes`} />
          </ListItem>:null}
        </ul>
      </aside>      
     {camera &&
      <div onClick={handleCloseCamera} id='overlay'
        className={classes.overlay}>
        <Webcam
        audio={false}
        screenshotFormat="image/jpeg"
        width='40%'
        videoConstraints={videoConstraints}
        style={{marginBottom:30}}
      >
          {({ getScreenshot }) => <>
            <CameraIcon onClick={() => {
              setSelfie(getScreenshot())
              playNotification(`${prodBaseURL}/cameraCapture.mp3`)
            }}
              className={classes.capturePhoto} fontSize='large' style={{marginBottom:30}} />
            <img className={classes.capturedPicture} width='300' height='174'
              style={{visibility:selfie?'visible':'hidden'}} src={selfie} alt='chosen pic'></img>
          </>}
        </Webcam>
      </div>}      
      <Typography
        className={classes.title}
        variant="h5"
        color="initial">
        Fill credentials*
      </Typography>      
      <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;