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

    let username = '', username2 = '', password = '', password2 = '';

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

        const resp = await workingWrapperO(() => rpc.Auth_signup(username, password));

        if (resp) {
            info_banner.set('Account created, please wait till an administrator approves it');
            $state.s = StateE.LOGIN;
        }
    }

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

<Card class="w-full max-w-lg">
    <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><Email /></InputAddon>
        <Input type="email" placeholder="Repeat email" bind:value={username2} 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={signup}>Singup</Button>
    </ButtonGroup>
</Card>
