import { useState } from "preact/hooks";
import { LoginForm } from "@common/components/LoginForm";
import { isLoggedIn, logout } from "@common/storage";
import { importStoredReducer } from "@common/hooks/useRemote";
import { STATE_KEY } from "../../contexts/state";
import styles from "../../assets/settings-modal.module.css";

export const LoginSettings = () => {
    const [loggedIn, setLoggedIn] = useState(isLoggedIn);
    const [imported, setImported] = useState(false);

    const handleLogin = () => setLoggedIn(true);

    const handleLogout = () => {
        logout();
        setLoggedIn(false);
    };

    const handleImport = () => {
        if (importStoredReducer(STATE_KEY)) {
            setImported(true);
            location.reload();
        }
    };

    if (loggedIn) {
        return (
            <div class={styles.form}>
                <span class={styles.label}>Logged in. Save data is synced to the server.</span>
                <button class={styles.buttonSecondary} onClick={handleImport} disabled={imported}>
                    {imported ? 'Imported' : 'Import settings from local storage'}
                </button>
                <button class={styles.buttonDanger} onClick={handleLogout}>Log out</button>
            </div>
        );
    }

    return <LoginForm onLogin={handleLogin} class={styles.form} />;
};
