import React, { useState, useEffect } from 'react';
import axios from 'axios'
import { Button, Form, Container, Alert, Spinner} from 'react-bootstrap';
import catchErrors from '../utils/catchErrors';
import { Redirect } from 'react-router-dom';
import Menu from '../Components/Menu';

const INIT_USER = {
    username: '',
    nickname: '',
    email: '',
    password: '',
}

function SingUp() {
    //const [validated, setValidated] = useState(false);
    const [user, setUser] = useState(INIT_USER)
    const [error, setError] = useState('')
    const [disabled, setDisabled] = useState(true)
    const [success, setSuccess] = useState(false)    
    const [loading, setLoading] = useState(false)

    useEffect(() => {
        const isUser = Object.values(user).every(el => Boolean(el))
        isUser ? setDisabled(false) : setDisabled(true)
    }, [user])

    function handleChange(event) {
        const { name, value } = event.target
        setUser({ ...user, [name]: value })
    }

    async function handleSubmit(event) {
        event.preventDefault();

        try {
            setLoading(true)
            setError('')
            await axios.post('/users/signup', user)
            setSuccess(true)
        } catch (error) {
            catchErrors(error, setError)
        } finally {
            setLoading(false)
        }
    }

    if (success) {
        console.log('success', success)
        alert('회원가입이 완료되었습니다!')
        return <Redirect to='/login' />
    }

    return (
        <>
            <Menu />
            <Form onSubmit={handleSubmit} className='vh-100 flex-column align-items-center justify-content-center mt-2'>
                <Container className="d-flex justify-content-center">
                    <div className="mt-5 p-5 shadow w-75">

                        <h2 className="text-center ">회원가입</h2>

                        <Form.Group controlId="formGroupUsername">
                            <Form.Label>이름</Form.Label>
                            <Form.Control
                                required
                                type="text"
                                name="username"
                                onChange={handleChange}
                                value={user.username}
                                placeholder="이름을 입력해주세요" />
                            <Form.Control.Feedback type="invalid">
                                필수 정보입니다! 이름을 입력해주세요!
                            </Form.Control.Feedback>
                        </Form.Group>

                        <Form.Group controlId="formGroupNickname">
                            <Form.Label>별명</Form.Label>
                            <Form.Control
                                required
                                type="text"
                                name="nickname"
                                onChange={handleChange}
                                value={user.nickname}
                                placeholder="별명을 입력해주세요" />
                            <Form.Control.Feedback type="invalid">
                                필수 정보입니다! 별명을 입력해주세요!
                            </Form.Control.Feedback>
                        </Form.Group>

                        <Form.Group controlId="formGroupEmail">
                            <Form.Label>이메일</Form.Label>
                            <Form.Control
                                required
                                type="email"
                                name="email"
                                onChange={handleChange}
                                value={user.email}
                                placeholder="이메일을 입력해주세요" />
                            <Form.Control.Feedback type="invalid">
                                필수 정보입니다! 이메일을 입력해주세요!
                            </Form.Control.Feedback>
                        </Form.Group>

                        <Form.Group controlId="formGroupPassword">
                            <Form.Label>비밀번호</Form.Label>
                            <Form.Control
                                required
                                type="password"
                                name="password"
                                onChange={handleChange}
                                value={user.password}
                                placeholder="비밀번호를 입력해주세요" />
                            <Form.Control.Feedback type="invalid">
                                필수 정보입니다! 비밀번호를 입력해주세요!
                            </Form.Control.Feedback>
                        </Form.Group>

                        <Button
                            disabled={disabled}
                            type='submit'
                            variant="outline"
                            size="lg"
                            className="mr-4"
                            style={{ border: "3px solid", borderColor: "#b49dc9", background: 'white', font: 'dark' }}
                            block>
                            {loading && <Spinner as='span' animation='border' size='sm' role='status' aria-hidden='true' style={{ color: "#b49dc9" }} />}가입</Button>
                        {error && <Alert variant='danger'>
                            {error}
                        </Alert>}
                    </div>
                </Container>
            </Form>
        </>
    )
}

export default SingUp