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

    useEffect(() => {
        const isUser = Object.values(user).every(el => Boolean(el))
        //Boolean : 참거짓 판별
        //every : every뒤에 함수값이 return하는 값이 모두 참일때만 true출력 -> element가 하나도 빈 문자열이 존재하지 않을때
        //empty string때만 false로 나옴.
        isUser ? setDisabled(false) : setDisabled(true)
    }, [user])

    function handleChange(event) {
        const { name, value } = event.target
        // console.log(name, value)
        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('')
            // const response = await fetch('/api/users/signup', {
            //     //post, get같은게 주어지지 않으면 기본적으로 fetch에 get요청함
            //     method: 'POST',
            //     headers: {
            //         'Content-Type': 'application/json'
            //     },
            //     body: JSON.stringify(user)
            // })
            // const data = await response.json()

            await axios.post('/users/signup', user)
            // 알아서 stringify하기 때문에 따로 해줄 필요 없음.
            // console.log(response.data)
            console.log(user)
            // ?????????hash 처리된 password가 저장되지 않았음

            // setUser(INIT_USER)
            setSucces(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