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

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

function LogIn() {
    const [user, setUser] = useState(INIT_USER)
    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))
        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 {
            setLoading(true)
            setError('')
            let res = await axios.post('/auth/login', user)
            handleLogin(res.data)
            setSucces(true)
        } catch (error) {
            catchErrors(error, setError)
        } finally {
            setLoading(false)
        }
        //server쪽에서 json형식으로 보낼것임
    }

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

    return (
        <>
            <Menu />
            <Form onSubmit={handleSubmit} className="vh-90 flex-column align-items-center justify-content-center mt-2" variant="dark">
                <div className="d-flex justify-content-center">
                    <div className="mt-5 p-5 mr-2" style={{ display: "flex", flexDirection: "column", borderStyle: "solid", borderRadius: "5px", borderColor: "#4A5D7E", backgroundColor: "#FFFFFF", padding: '15px', position: "relative" }}>
                        <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"
                            size="lg"
                            className="mr-4"
                            style={{ border: "3px solid", borderColor: "#b49dc9", background: 'white', font: 'dark' }}
                            block>
                            {loading && <Spinner as='span' animation='border' size='sm' role='status' aria-hidden='true' style={{ color: "#b49dc9" }} />} {' '} 로그인
                                </Button>
                        {error && <Alert variant='danger'>
                            {error}
                        </Alert>}
                    </div>
                </div>
            </Form>
        </>
    );
}

export default LogIn