import React, { useState } from 'react';
import axios from 'axios';
import cl from './ModalLevel.module.css';
import '../../AddLevel.css';

const hostURL = "http://localhost:8080";
const host = hostURL + "/api/1.0/level";

const ModalLevel = ({data, visible, setVisible}) => {

    //для обновления уровня
    const [level, setLevel] = useState(data.level);

    //для контроля видимости модалки
    const rootClasses = [cl.myModal];

    if(visible)
    {
        rootClasses.push(cl.active);
    }

    const getTokenForHeader = function () {
        return "Bearer " + localStorage.getItem("token");
    }    

    //добавление нового уровня
    const updateLevel = async function () {
        const requestParams = {
            method: "PUT",
            headers: {
                "Content-Type": "application/json",
                "Authorization": getTokenForHeader(),
            }
        };
        console.log(level);
        const requestUrl = host + `/${data.id}?Level=${level}`;
        const response = await fetch(requestUrl, requestParams);
        console.log("Обновление успешно!")
        setVisible(false);
    }

    return (
        <div className={rootClasses.join(' ')} onClick={() => setVisible(false)}>
            <div className={cl.myModalContent} onClick={(e) => e.stopPropagation()}>
                <input
                    className="add-level-input"
                    value={level}
                    onChange={e => setLevel(e.target.value)}
                />
                <button
                    className={cl.modalButton} 
                    type="button"
                    onClick={event => updateLevel()}
                >
                    Сохранить  
                </button>
            </div>
        </div>
    );
};

export default ModalLevel;
