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

    let enter_key = false;
    let username = '', key = '', password = '', password2 = '';

    async function sendKey() {
        if (await workingWrapper(() => rpc.Auth_send_recovery_key(username)) == null)
            return;
        info_banner.set('A message has been sent');
        enter_key = true;
    }

    async function changePw() {
        if (password != password2) {
            error_banner.set('Password doesn\'t match');
            return;
        }

        if (await workingWrapperO(() => rpc.Auth_reset_password(key, password)))
            $state.s = StateE.LOGIN;
    }

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

<Card class="w-full max-w-lg">
    <h3 class="mb-6">Reset password</h3>
    {#if enter_key}
        <ButtonGroup class="w-full mb-4">
            <InputAddon><EmailNew /></InputAddon>
            <Input type="text" placeholder="Recovery key" bind:value={key} on:keyup={keyUp}></Input>
        </ButtonGroup>
        <ButtonGroup class="w-full mb-2">
            <InputAddon><Password /></InputAddon>
            <Input type="password" placeholder="Password" bind:value={password} on:keyup={keyUp}></Input>
        </ButtonGroup>
        <ButtonGroup class="w-full mb-4">
            <InputAddon><Password /></InputAddon>
            <Input type="password" placeholder="Repeat password" bind:value={password2} 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.LOGIN)}>Login</Button>
            <Button class="flex-1 flex-grow" color="primary" on:click={changePw}>Change password</Button>
        </ButtonGroup>
    {:else}
        <ButtonGroup class="w-full mb-4">
            <InputAddon><Email /></InputAddon>
            <Input type="email" placeholder="Email" bind:value={username} 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.LOGIN)}>Login</Button>
            <Button class="flex-1 flex-grow" color="primary" on:click={sendKey}>Send recovery key</Button>
            <Button class="flex-1 flex-grow" color="primary" outline on:click={() => (enter_key = true)}>Enter key</Button>
        </ButtonGroup>
    {/if}
</Card>

<style>

</style>
