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

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

const ModalNation = ({data, visible, setVisible}) => {
  //для обновления уровня
  const [nation, setNation] = useState(data.nation);

  const nullId = 0;

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

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

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

  const updateNation = async function () {
    const requestParams = {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "Authorization": getTokenForHeader(),
        }
    };
    const requestUrl = host + `/${data.id}?nation=${nation}&tankId=${nullId}`;
    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-nation-input"
                  value={nation}
                  onChange={e => setNation(e.target.value)}
              />
              <button
                  className={cl.modalButton} 
                  type="button"
                  onClick={event => updateNation()}
              >
                  Сохранить  
              </button>
          </div>
      </div>
  );
}

export default ModalNation
