<script lang="ts">
    import {Button, ButtonGroup, Card, Input, InputAddon} from 'flowbite-svelte';
    import {Email, Password} from 'carbon-icons-svelte';
    import {changeStateFunction, rpc, state, StateE, token, workingWrapperR, api} from '../store';

    let ask_tfa = false;
    let username = '', password = '', tfa = '';

    async function login() {
        const resp = await workingWrapperR<api.LoginResponse>(() => rpc.Auth_login(username, password, ask_tfa ? tfa : null));
        if (!resp) return;
        if (resp.otp_needed) {
            ask_tfa = true;
            return;
        }
        token.set(resp.token);
        state.set({s: StateE.VIEW, view_node: 0});
    }

    function keyUp(e: KeyboardEvent) {
        if (e.key == 'Enter') login();
    }
</script>

<Card class="w-full max-w-lg">
    {#if ask_tfa}
        <h3>Two factor authentication</h3>
        <ButtonGroup class="w-full mb-4">
            <InputAddon><Password /></InputAddon>
            <Input type="text" placeholder="Code" bind:value={tfa} on:keyup={keyUp}></Input>
        </ButtonGroup>
        <Button class="w-full" color="primary" on:click={login}>Login</Button>
    {:else}
        <h3 class="mb-6">Sign in</h3>
        <ButtonGroup class="w-full mb-2">
            <InputAddon><Email /></InputAddon>
            <Input type="email" placeholder="Email" bind:value={username} on:keyup={keyUp}></Input>
        </ButtonGroup>
        <ButtonGroup class="w-full mb-4">
            <InputAddon><Password /></InputAddon>
            <Input type="password" placeholder="Password" bind:value={password} on:keyup={keyUp}></Input>
        </ButtonGroup>
        <ButtonGroup class="w-full flex flex-nowrap">
            <Button class="flex-1 flex-grow" color="primary" outline on:click={changeStateFunction(StateE.SIGNUP)}>Signup</Button>
            <Button class="flex-1 flex-grow" color="primary" on:click={login}>Login</Button>
            <Button class="flex-1 flex-grow" color="primary" outline on:click={changeStateFunction(StateE.RESET_PASSWORD)}>Forget password</Button>
        </ButtonGroup>
    {/if}
</Card>
