import React, { useState, useEffect } from 'react';
import axios from 'axios'
import { Button, Form, Container, Alert, Navbar } 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)

    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();

        //빈문자열 입력 시 오류 문자 출력
        //const form = event.currentTarget;
        //if (form.checkValidity() === false) {
        //    event.preventDefault();
        //    event.stopPropagation();
        //    //event.stopPropagation() : 이벤트 캡쳐링과 버블링에 있어 현재 이벤트 이후의 전파를 막습니다.
        //}
        //setValidated(true);
        // console.log(user)

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

    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-success"
                            size="lg"
                            className="mr-4"
                            block>가입</Button>
                        {error && <Alert variant='danger'>
                            {error}
                        </Alert>}
                    </div>
                </Container>
            </Form>
        </>
    )
}

export default SingUp