import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { Button } from '@material-ui/core';
import { LoadingButton } from '@material-ui/lab';
import axios from 'axios';

import IconButton from '@mui/material/IconButton';
import PhotoCamera from '@mui/icons-material/PhotoCamera';


const Register = () => {
    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [agent, setAgent] = useState('');
    const [imgUri, setImageUri] = useState(''); 

    const [errors, setErrors] = useState({})
    const [err_400, setErr400] = useState(false)

    const handleSubmit = (e) => {
        e.preventDefault();
        if(!validateForm()) return;
        const formdata = new FormData();
        formdata.append('firstName', firstName);
        formdata.append('lastName', lastName);
        formdata.append('email', email);
        formdata.append('password', password);
        formdata.append('agent', agent);
        axios.post('/register/c-account', formdata)
        .then(response => {
            if(response.data.status_code==200){
                window.location.href = '/register/c-account/complete';
            }
            else if(response.data.status_code==400){
                window.location.href = '/register/c-account/error';
            }
            else if(response.data.status_code==500){
                window.location.href = '/unknown-error';
            }
        })
        .catch(err=>{setErr400(true)})
    }

    const validateForm = () => {
        let errors = {};
        let formIsValid = true;
        if (email.length == 0) { formIsValid = false; errors["email"] = 'Required'; }
        else {
          //regular expression for email validation
            var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
            if (!pattern.test(email)) {
                formIsValid = false;
                errors["email"] = true;
            }
            else {
                errors['email'] = false;
            }
        }

        if(!imgUri){ formIsValid = false;  errors['avatar'] = true;  }
        else errors['avatar'] = false;

        if(firstName.length == 0){ formIsValid = false;  errors['firstName'] = true;  }
        else errors['firstName'] = false;

        if(lastName.length == 0){ formIsValid = false;  errors['lastName'] = true;  }
        else errors['lastName'] = false;

        if(password.length < 8){ formIsValid = false;  errors['password'] = true;  }
        else errors['password'] = false;

        if(agent.length == 0){ formIsValid = false;  errors['agent'] = true;  }
        else errors['agent'] = false;

        setErrors(errors);
        return formIsValid;
    }

    const handleImageChange = (e) => {

        e.preventDefault();
        let reader = new FileReader();
        let _file = e.target.files[0];

        reader.readAsDataURL(_file);

        reader.onloadend = () => {
            setImageUri(reader.result);
        };
    };

	return (
        <form onSubmit={handleSubmit} noValidate>
            <p className="text-center font-weight-bold ft-20">本登録</p>

            <div className="mt-25-px">
                <input type="file" id="avatar" name="avatar" className="d-none" accept=".png, .jpg, .jpeg" onChange={(e) => handleImageChange(e)}/>
                <div className={`avatar-wrapper  ${ errors['avatar'] && "is-invalid c-input__target" }` }>
                    <label htmlFor="avatar" className='avatar-label'>
                        <IconButton color="primary" aria-label="upload picture" component="span" className="bg-color-2 shadow-sm">
                            <img src="/assets/img/icon/camera.svg" width="16" height="16"/>
                        </IconButton>
                    </label>
                    {  
                        imgUri && 
                            <img src={imgUri} alt="" width ="100%" height="100%" style={{borderRadius:'50%'}}/>  
                    }
                </div>
                {   
                    errors['avatar']  && 
                        <span className="l-alert__text--red ft-16 ft-md-14">Required.</span>  
                }
            </div>
            
            <div className="c-input mt-25-px">
                <label htmlFor="firstname"  className="c-input__label ft-12"> 姓 </label>
                <input type="text" name="firstname" id="firstname"  className={`w-100 c-input__edit ${ errors['firstName'] && "is-invalid c-input__target" }`}  value={firstName} onChange={e=>setFirstName(e.target.value)}/>
                {
                    errors['firstName'] &&
                        <span className="l-alert__text--red ft-16 ft-md-14">Required.</span>
                }
            </div>

            <div className="c-input mt-40-px">
                <label htmlFor="lastname" className="c-input__label"> 名 </label>
                <input type="text" name="lastname" id="lastname"  className={`w-100 c-input__edit ${ errors['lastName'] && "is-invalid c-input__target" }`} value={lastName} onChange={e=>setLastName(e.target.value)}/>
                {
                    errors['lastName'] &&
                        <span className="l-alert__text--red ft-16 ft-md-14">Required.</span>
                }
            </div>

            <div className="c-input mt-40-px">
                <label htmlFor="email"   className="c-input__label"> メールアドレス </label>
                <input type="email" name="email" id="email"  className = {`w-100 c-input__edit ${ errors['email'] && "is-invalid c-input__target" }`}  value={email} onChange={e=>setEmail(e.target.value)}/>
                {
                    errors['email'] && 
                        <span className="l-alert__text--red ft-16 ft-md-14">Required.</span>
                }
            </div>

            <div className="c-input mt-40-px">
                <label htmlFor="password" className="c-input__label"> パスワード </label>
                <input type="password" name="password" id="password"  className = {`w-100 c-input__edit ${ errors['password'] && "is-invalid c-input__target" }`}  value={password} onChange={e=>setPassword(e.target.value)}/>
                {
                    errors['password'] &&
                        (password.length == 0 ?
                            <span className="l-alert__text--red ft-16 ft-md-14">Required.</span>
                            :<span className="l-alert__text--red ft-16 ft-md-14">At least 8 letters.</span>)
                }
            </div>

            <div className="c-input mt-40-px">
                <label htmlFor="agent"   className="c-input__label"> 所屈している会社名を記載 </label>
                <input type="text" name="agent" id="agent"  className = {`w-100 c-input__edit ${ errors['agent'] && "is-invalid c-input__target" }`}  value={agent} onChange={e=>setAgent(e.target.value)}/>
                {
                    errors['agent'] &&
                        <span className="l-alert__text--red ft-16 ft-md-14">Required.</span>
                }
            </div>
            
            <div className="mt-4">
                <LoadingButton type="submit" fullWidth className="p-3 rounded-20 ft-15 font-weight-bold text-black bg-color-2">本登録</LoadingButton>
            </div>
        </form>
	)
}


if(document.getElementById('sign-up')){
	ReactDOM.render(
		<Register />,
		document.getElementById('sign-up')
	)
}