import './css/loginform.css';
import React, { useState } from 'react';
import { Modal, Form, Button, } from 'react-bootstrap';
import axios from 'axios';

const LoginForm = ({ showLoginForm, setShowLoginForm, setShowRegisterForm, setAlertType, setAlertMessage, setShowAlert, setLogged }) => {

    const handleClose = () => {
        setUserData(() => ({
            username: "",
            password: "",
        }));
        setShowLoginForm(false);
    };

    const handleShow = () => setShowLoginForm(true);

    const [userData, setUserData] = useState({
        username: "",
        password: "",
    });

    const handleShowRegistration = () => {
        setShowLoginForm(false);
        setShowRegisterForm(true);
    };

    const handleUsernameInputChange = (e) => {
        setUserData((values) => ({
            ...values,
            username: e.target.value
        }));
    };

    const handlePasswordInputChange = (e) => {
        setUserData((values) => ({
            ...values,
            password: e.target.value
        }));
    };

    const login = () => {
        axios.post('http://localhost:8080/pa165/login', { userName: userData.username, password: userData.password }, {
            headers: {
                accept: '*/*',
                'Content-Type': 'application/json',
            }
        })
            .then(function (response) {
                if (response.data.userId == null) {
                    localStorage.setItem('userId', 1);
                } else {
                    localStorage.setItem('userId', response.data.userId);
                }
                localStorage.setItem('isAdmin', response.data.admin);
                localStorage.setItem('token', response.data.token);
                setLogged(true);
            })
            .catch((error) => {
                setAlertType(1);
                setShowAlert(true);
                if (error.response === null) {
                    setAlertMessage("No response from server");
                } else if (error.response.status === 401) {
                    setAlertMessage("Wrong username or password");
                } else {
                    setAlertMessage("Login failed");
                }
            });
    }

    const handleLogin = () => {
        if (userData.username === "") {
            setAlertType(1);
            setAlertMessage("Username is required!");
            setShowAlert(true);
        }
        else if (userData.password === "") {
            setAlertType(1);
            setAlertMessage("Password is required!");
            setShowAlert(true);
        }
        else {
            login();
            handleClose();
        }
    };

    return (
        <>
            <Modal show={showLoginForm} onHide={handleClose}>
                <Modal.Header closeButton>
                    <Modal.Title>Log in</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <Form>
                        <Form.Group className="mb-3" controlId="LoginForm.Username">
                            <Form.Label>Username</Form.Label>
                            <Form.Control
                                type="text"
                                placeholder="Nickname"
                                value={userData.username}
                                onChange={handleUsernameInputChange}
                                autoFocus
                            />
                        </Form.Group>
                        <Form.Group className="mb-3" controlId="LoginForm.Password">
                            <Form.Label>Password</Form.Label>
                            <Form.Control
                                type="password"
                                value={userData.password}
                                onChange={handlePasswordInputChange}
                                placeholder="Password"
                            />
                        </Form.Group>
                    </Form>
                </Modal.Body>
                <Modal.Footer>
                    <Button variant="secondary" onClick={handleClose}>
                        Close
                    </Button>
                    <Button variant="secondary" onClick={handleShowRegistration}>
                        Sign up
                    </Button>
                    <Button variant="primary" onClick={handleLogin}>
                        Log in
                    </Button>
                </Modal.Footer>
            </Modal>
        </>
    );
}

export default LoginForm;