import React from 'react';
import {useState} from "react";
import api from '../api'
import {useNavigate} from "react-router-dom";
import {ACCESS_TOKEN, REFRESH_TOKEN, USERNAME, DATE_TOGGLE} from "../constants.js";

function LoginForm({route, method}) {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();

    const handleLogin = async (e) => {
        setLoading(true)
        e.preventDefault();

        try {
            const response = await api.post('token/', {username, password})
            if (response.status === 200) {
                localStorage.setItem(ACCESS_TOKEN, response.data.access)
                localStorage.setItem(REFRESH_TOKEN, response.data.refresh)
                localStorage.setItem(USERNAME, username)
                localStorage.setItem(DATE_TOGGLE, new Date().toLocaleDateString());
                navigate('/')
            } else {
                navigate('/login')
            }
        } catch (error) {
            alert(error)
        } finally {
            setLoading(false)
        }
    }

    return (
        <div className="d-flex align-items-center justify-content-center p-2">
            <form onSubmit={handleLogin} className='form-control'>
                <h3 className="p-2">Team Member Login</h3>
                <input
                    type={"text"}
                    className='form-control'
                    value={username}
                    onChange={(e) => {setUsername(e.target.value)}}
                    placeholder="Username"/>
                <input
                    type={"password"}
                    className='form-control'
                    value={password}
                    onChange={(e) => {setPassword(e.target.value)}}
                    placeholder="Password"
                />
                <div className="d-flex align-items-center">
                    <button className="m-2" type="submit">Login</button>
                    {loading && <div className="m-2 spinner-border"></div>}
                </div>

            </form>
        </div>
    )
}

export default LoginForm
