import ReactDOM from 'react-dom';
import * as React from "react";
import {TextField} from "@mui/material";
import {EncryptStorage} from "storage-encryption";
import {useState} from "react";
let encryptStorage = new EncryptStorage('test'); // TODO la clef doit venir de l'utilisateur

const app = document.getElementById('first');
const word = "shikiryu";
let csrf,
    url = "";

if (app) {
    url   = "" + app.getAttribute('data-url');
    csrf  = "" + app.getAttribute('data-csrf');
    ReactDOM.render(<FirstPage/>, app);
}

export default function FirstPage() {
    const [passphrase, setPassphrase] = useState("");
    const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        sessionStorage.setItem("key", passphrase);
        encryptStorage = new EncryptStorage(passphrase);
        encryptStorage.encrypt("checkword", word);
        let encryptedFormData = new FormData();
        encryptedFormData.append("checkword", ""+localStorage.getItem("checkword"));
        encryptedFormData.append('_token', csrf);

        const response = await fetch(url, {
            method: 'POST',
            body: encryptedFormData
        });

        const json = await response.json(); // TODO redirect if success

        if (json.success) {
            location.href = "/diary/public/pages"
        }
    };

    const updatePassphrase = (e: React.ChangeEvent<HTMLInputElement>) => {
        setPassphrase(e.target.value);
    };

    return (
        <div>
            <div className="container">
                <div className="row justify-content-center">
                    <div className="col-md-8">
                        <form action={url} id="postPage" method="post" onSubmit={onSubmit}>
                            <TextField id="filled-basic" label="Passphrase" variant="filled" onInput={updatePassphrase}/>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
}
