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

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, setSucces] = 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();
        }
        setValidated(true);
        // console.log(user)

        try {
            setError('')
            await axios.post('/users/signup', user)
            alert("회원가입이 완료되었습니다!")
            setSucces(true)
        } catch (error) {
            catchErrors(error, setError)
        }
    }

    if (success) {
        console.log('success', success)
        return <Redirect to='/login' />
    }


    return (
        <>
            <Navbar bg="dark" variant="dark">
                    <Navbar.Brand>YDK Messenger</Navbar.Brand>
                </Navbar>

            <Form noValidate validated={validated} 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