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

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

function LogIn() {
    const [validated, setValidated] = useState(false);
    const [user, setUser] = useState(INIT_USER)
    //로딩, 에러, diserved 상태 넣어야됨.
    const [disabled, setDisabled] = useState(true)
    const [error, setError] = useState('')
    const [success, setSucces] = useState(false)
    const [loading, setLoading] = 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();
        // }
        // setValidated(true);

        try {
            setLoading(true)
            setError('')
            const response = await axios.post('/auth/login', user)
            // 알아서 stringify하기 때문에 따로 해줄 필요 없음.
            console.log(response.data)
            handleLogin(response.data.userId)
            setSucces(true)
        } catch (error) {
            catchErrors(error, setError)
            //setError(error.response.data)
            //error객체가 들어감. 
        } finally {
            setLoading(false)
        }
        //server쪽에서 json형식으로 보낼것임
    }

    //success시 링크이동
    if (success) {
        console.log('success', success)
        alert('로그인 되었습니다!')
        return <Redirect to='/' />
    }

    return (
        <>
            <Menu />

            <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="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 || loading}
                            type="submit"
                            variant="outline-success"
                            size="lg"
                            className="mr-4"
                            block>
                            {loading && <Spinner as='span' animation='border' size='sm' role='status' aria-hidden='true' />} {' '} 로그인
                                </Button>

                        <Link to="./signup">
                            <h6 type="button" className="text-right mt-2" style={{ cursor: 'pointer' }}>회원가입</h6>
                        </Link>
                        {error && <Alert variant='danger'>
                            {error}
                        </Alert>}
                    </div>
                </Container>
            </Form>
        </>
    );
}

export default LogIn