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';



const Contact = () => {
    const [email, setEmail] = useState('');
    const [message, setMessage] = useState('');

    const [errors, setErrors] = useState({ email:'', message:'' })
    const [err_msg, setErrMsg] = useState('')

    const handleSubmit = (e) => {
        e.preventDefault();
        setErrMsg('');
        if(!validateForm()) return;
        const formdata = new FormData();
        formdata.append('email', email);
        formdata.append('message', message);
        axios.post('/contacts/register/', formdata)
        .then(response => {
            if(response.data.status_code==200){
                window.location.href = '/contact-us/complete';
            }
        })
        .catch(err=>{setErrMsg('Server Error!')});
        
    }

    const validateForm = () => {
        let errors = {};
        let formIsValid = true;
        if (email.length == 0) {
          formIsValid = '';
          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"] = "Wrong Email Address";
            }
            else {
                errors['email'] = '';
            }
        }
        if(message.length == 0){ formIsValid = false;  errors['message'] = 'Required'; }
        else errors['message'] = '';

        setErrors(errors);
        return formIsValid;
    }

	return (
        <form onSubmit={handleSubmit} noValidate>
            <p className="text-center font-weight-bold ft-20">お問い合わせ</p>
            {
                err_msg && 
                    <span className="my-4 l-alert__text--red ft-16 ft-md-14">{err_msg}</span> 
            }
            <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'].length != 0 && "is-invalid c-input__target" } `}  value={email} onChange={e=>setEmail(e.target.value)} autoFocus/>
                {
                    errors['email'].length != 0 &&
                        <span className="l-alert__text--red ft-16 ft-md-14">{errors['email']}</span> 
                }
            </div>

            <div className="c-input mt-40-px">
                <label htmlFor="message"   className="c-input__label"> お問合せ内容 </label>
                <textarea name="message" id="message" rows="7" className={`w-100 c-input__edit  ${ errors['message'].length != 0 && "is-invalid c-input__target" } `}  value={message} onChange={e=>setMessage(e.target.value)}/>
                {
                    errors['message'].length != 0 &&
                        <span className="l-alert__text--red ft-16 ft-md-14">{errors['message']}</span> 
                }
            </div>
            <div className="mt-3">
                <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('contact')){
	ReactDOM.render(
		<Contact />,
		document.getElementById('contact')
	)
}