import { useState, useEffect } from 'react'
import './Home.css'
import Request from '../Request.jsx'
import {useTranslation} from "react-i18next";

let bonusItems = [];

function getMigrationID(uid) {
    return uid.toString()
    .replaceAll('1', "A")
    .replaceAll('2', "G")
    .replaceAll('3', "W")
    .replaceAll('4', "Q")
    .replaceAll('5', "Y")
    .replaceAll('6', "6")
    .replaceAll('7', "I")
    .replaceAll('8', "P")
    .replaceAll('9', "U")
    .replaceAll('0', "M")
    + "7";
}

function Bonus() {
    const [inputValue, setInputValue] = useState('');
    const error = useState("");
    const { t } = useTranslation();
    
    let itemz = [];
    bonusItems.forEach((e) => {
        itemz.push(e.master_login_bonus_id);
    })
    
    const [submittedItems, setSubmittedItems] = useState(itemz);
    
    const handleSubmit = async (event) => {
        event.preventDefault();
        let input = parseInt(inputValue.trim());
        if (isNaN(input) || submittedItems.includes(input)) return;
        let resp = await Request("/api/webui/submitLoginBonus", {
            bonus_id: input,
            is_add: true
        });
        if (resp.result !== "OK") {
            error[1](resp.message);
            return;
        }
        error[1]("");
        setSubmittedItems([...submittedItems, resp.id]);
        setInputValue('');
    };

    const handleRemoveItem = async (index) => {
        const updatedItems = [...submittedItems];
        let resp = await Request("/api/webui/submitLoginBonus", {
            bonus_id: updatedItems[index],
            is_add: false
        });
        if (resp.result !== "OK") {
            error[1](resp.message);
            return;
        }
        error[1]("");
        updatedItems.splice(index, 1);
        setSubmittedItems(updatedItems);
    };

    return (
        <div>
          <h2>{t('current_bonus')}</h2>
          <div id="error"> { error[0] ? <p>Error: { error[0] } </p> : <p></p> } </div>
          <ul>
            {submittedItems.map((item, index) => (
                    <li key={index}>
                        {item}
                        <button onClick={() => handleRemoveItem(index)}>X</button>
                    </li>
            ))}
          </ul>
            <form onSubmit={handleSubmit}>
            <input
              type="text"
              value={inputValue}
              onChange={(event) => setInputValue(event.target.value)}
              placeholder={t('enter_bonus_id')}
            />
            <button type="submit">{t('submit')}</button>
          </form>
          <p>{t('find_bonus_in_url')} <a href="https://git.ethanthesleepy.one/ethanaobrien/ew/src/branch/main/src/router/databases/json/login_bonus.json">{t('here')}</a>. {t('should_input')} <code>id</code></p>
        </div>
    );
}

function Home() {
    const [user, userdata] = useState();
    const [inputValue, setInputValue] = useState('');
    const [serverTime, setServerTime] = useState('');
    const error = useState("");
    const { t } = useTranslation();
    
    const logout = () => {
        window.location.href = "/webui/logout";
    }
    const downloadFile = (contents, name) => {
        let a = document.createElement("a");
        a.href = URL.createObjectURL(new Blob([contents], {type: "application/json"}));
        a.download = name;
        a.click();
    }
    const expor = async (e) => {
        e.preventDefault();
        let resp = await Request("/api/webui/export");
        if (resp.result !== "OK") {
            error[1](resp.message);
            return;
        }
        downloadFile(resp.data.userdata, "userdata.json");
        downloadFile(resp.data.userhome, "userhome.json");
        downloadFile(resp.data.missions, "missions.json");
        downloadFile(resp.data.sifcards, "sifcards.json");

    }
    const handleSubmit = async (event) => {
        event.preventDefault();
        let time = Math.round(new Date(inputValue.trim()).getTime() / 1000);
        if (inputValue.trim() === "0") {
            time = 0;
        }
        if (time < -1 || isNaN(time)) return;
        let resp = await Request("/api/webui/set_time", {
            timestamp: time
        });
        if (resp.result !== "OK") {
            error[1](resp.message);
            return;
        }
        error[1]("");
        if (time === 0) {
            setServerTime(new Date().toString());
        } else {
            setServerTime((new Date(time * 1000)).toString());
        }
        setInputValue('');
    };
    
    useEffect(() => {
        if (user) return;
        (async () => {
            let resp = await Request("/api/webui/userInfo");
            if (resp.result !== "OK") {
                window.location.href = "/?message=" + encodeURIComponent(resp.message);
                return;
            }
            let user = resp.data.userdata;
            bonusItems = resp.data.loginbonus.bonus_list;
            /*
            bonusItems = [{"master_login_bonus_id":1,"day_counts":[1,2],"event_bonus_list":[]}];
            let user = {
                user: {
                    id: 1,
                    rank: 3,
                    exp: 10,
                    last_login_time: 5
                },
                server_time_set: new Date()
                time: new Date()
            }*/
            if (resp.data.time === 0) {
                setServerTime(new Date().toString());
            } else {
                let deltaTime = new Date().getTime() - resp.data.server_time_set * 1000
                let gameTime = resp.data.time * 1000 + deltaTime
                setServerTime((new Date(gameTime)).toString());
            }
            
            userdata(
                <div>
                    <p>SIF2 ID: { user.user.id } </p>
                    <p>{t('migration_id')}: { getMigrationID(user.user.id) } </p>
                    <p>{t('level')}: { user.user.rank } ({ user.user.exp } exp)</p>
                    <p>{t('last_login_time')}: { (new Date(user.user.last_login_time * 1000)).toString() } </p>
                    <Bonus />
                </div>
            );
        })();
    });
  
    return (
        <div id="home">
            <button id="logout" onClick={expor}>{t('export_account')}</button><br/><br/><br/>
            <button id="logout" onClick={logout}>{t('logout')}</button>
            <h1>{t('home')}</h1>
            
            { user ? <div> 
                { user } 
                <h2>{t('server_time')}</h2>
                <div id="error"> { error[0] ? <p>{t('error')}: { error[0] } </p> : <p></p> } </div>
                <p>{t('current_game_time')} { serverTime }. {t("set_time_hint")}</p>
                <form onSubmit={handleSubmit}>
                    <input
                        type="text"
                        value={inputValue}
                        onChange={(event) => setInputValue(event.target.value)}
                        placeholder={t('input_server_time')}
                    />
                    <button type="submit">{t('submit')}</button>
                </form></div>
            : <p>{t('loading')}</p> }
        </div>
    );
}

export default Home;
