import React, { useState, useEffect } from 'react'
import {  Col, Container, Form, Row, Button, Alert } from "react-bootstrap"
import axios from "axios"
import catchErrors from '../utils/catchErrors'
import { Redirect } from 'react-router-dom'

const INIT_USER = {
    name: '',
    email: '',
    password: ''
}

function Signup() {
    const [user, setUser] = useState(INIT_USER)
    const [disabled, setDisabled] = useState(true)
    const [error, setError] = useState('')
    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()
        try {
            setError('')
            const response = await axios.post('/api/users/signup', user)
            console.log(response.data)
            console.log(user)
            // setUser(INIT_USER)
            setSuccess(true)
        } catch (error) {
            console.log(error)
            catchErrors(error, setError)
        }
    }

    if (success) {
        alert('회원가입 되었습니다.')
        return <Redirect to='/'/>
    } 

    return (
        <Container>
            <Row className= 'vh-100 flex-column align-items-center justify-content-center'>
            <h2>회원가입</h2>
                <Col md={5}>
            {error && <Alert variant='danger'>
                {error}
            </Alert>}
                <Form onSubmit={handleSubmit}>
                    <Form.Group>
                        <Form.Label>이름</Form.Label>              
                        <Form.Control name='name' value={user.name} onChange={handleChange}/>
                    </Form.Group>
                    <Form.Group>
                        <Form.Label>이메일</Form.Label>
                        <Form.Control name='email' type='email'value={user.email} onChange={handleChange}/>
                    </Form.Group>
                    <Form.Group>
                        <Form.Label>비밀번호</Form.Label>
                        <Form.Control name='password' type='password' value={user.password} onChange={handleChange}/>
                    </Form.Group>
                    <Button disabled={disabled} type='submit' block>확인</Button>
                </Form>
                </Col>
            </Row>
        </Container>
    )
}

export default Signup
