import React, { useState, useEffect } from 'react';
import axios from 'axios';
import cl from './ModalTank.module.css';
import '../../AddTank.css';

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

const ModalTank = ({data, visible, setVisible}) => {
    //для обновления танка
    const [tankName, setTankName] = useState(data.name);

    const [tankCost, setTankCost] = useState(data.cost);

    const [chooiceNation, setChoiceNation] = useState(data.nation.id);

    const [chooiceLevel, setChoiceLevel] = useState(data.nation.id);

    const [nationItems, setNationItems] = useState([]);

    const [levelItems, setLevelItems] = useState([]);
   
    //для контроля видимости модалки
    const rootClasses = [cl.myModal];
  
    if(visible)
    {
        rootClasses.push(cl.active);
    }

    //загрузка всего необходимого при старте
    useEffect(() => {
        getLevels();
        getNations();
    }, [])

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

    const getNations = async function () {
        const requestParams = {
            method: "GET",
            headers: {
                "Authorization": getTokenForHeader(),
            }
        };
        const requestUrl = host + `nation/getNations`;
        const response = await fetch(requestUrl, requestParams);
        const data = await response.json();
        console.log(data);
        setNationItems(data);
    }

    //загрузка всех имеющихся уровней при старте
    const getLevels = async function () {
        const requestParams = {
            method: "GET",
            headers: {
                "Authorization": getTokenForHeader(),
            }
        };
        const requestUrl = host + `level/getLevels`;
        const response = await fetch(requestUrl, requestParams);
        const data = await response.json();
        console.log(data);
        setLevelItems(data);
    }

    const updateTank = async function () {
        const requestParams = {
            method: "PUT",
            headers: {
                "Content-Type": "application/json",
                "Authorization": getTokenForHeader(),
            }
        };
        console.log(data);
        console.log(chooiceNation);
        const requestUrl = host + `tank/${data.id}?firstName=${tankName}&nationId=${chooiceNation}&levelId=${chooiceLevel}&cost=${tankCost}`;
        const response = await fetch(requestUrl, requestParams);
        console.log("Обновление успешно!")
        setVisible(false);
    }

    const getChoiceNation = (newId) => {
        setChoiceNation(nationItems[newId - 1].id);
    }

    const getChoiceLevel = (newId) => {
        setChoiceLevel(levelItems[newId - 1].id);
    }


  return (
    <div className={rootClasses.join(' ')} onClick={() => setVisible(false)}>
          <div className={cl.myModalContent} onClick={(e) => e.stopPropagation()}>
                <p>
                    Название:
                    <input
                        className="add-tank-input"
                        value={tankName}
                        onChange={e => setTankName(e.target.value)}
                    />
                </p>
                <p>
                    Стоимость:
                    <input
                        className="add-tank-input"
                        value={tankCost}
                        onChange={e => setTankCost(e.target.value)}
                    />
                </p>
                <p style={{fontWeight: "900"}}>
                        Выберите нацию:
                        <select
                            onChange={(event) => getChoiceNation(event.target.selectedIndex)}
                        >
                            <option selected>Выберите нацию</option>
                            {nationItems.map((nationItem) =>
                                <option
                                    value={nationItem.nation}
                                    key={nationItem.id}
                                >
                                    {nationItem.nation} 
                                </option>
                            )}
                        </select>
                    </p>
                    <p style={{fontWeight: "900"}}>
                        Выберите уровень:
                        <select style={{marginTop: "10px"}}
                            onChange={(event) => getChoiceLevel(event.target.selectedIndex)}
                        >
                            <option selected>Выберите уровень</option>
                            {levelItems.map((levelItem) =>
                                <option
                                    value={levelItem.level} 
                                    key={levelItem.id}
                                >
                                    {levelItem.level} 
                                </option>
                            )}
                        </select>
                    </p>
                <button
                    className={cl.modalButton} 
                    type="button"
                    onClick={event => updateTank()}
                >
                    Сохранить  
                </button>
          </div>
      </div>
  );
}

export default ModalTank
