<script lang="ts">
    import Button from "$lib/ui/button.svelte";
    import { clear_auth_session, init_auth_session, do_import } from "./methods.remote";
    import type { PageProps } from "./$types";
    import type { ImportForm } from "$lib/shared";

    let { data }: PageProps = $props();
    let navigating = $state(false);
    let form = $state<ImportForm>({
        budgetId: "",
        mappings: [],
        dryRun: true,
    });

    async function run() {
        if (!form.mappings.length) {
            return;
        }
        await do_import(form);
    }

    async function authorize() {
        navigating = true;
        const url = await init_auth_session();
        location.href = url;
    }

    async function logout() {
        navigating = true;
        await clear_auth_session();
        location.reload();
    }

    function onMappingChanged(sb1Id: string, actualId: string) {
        let mappings = form.mappings;
        if (mappings.find((c) => c.sb1Id === sb1Id)) mappings = mappings.filter((c) => c.sb1Id !== sb1Id);
        mappings.push({ sb1Id, actualId });
        form.mappings = mappings;
    }
</script>

<main>
    {#if data.sb1.accounts?.length}
        <form onsubmit={run}>
            <h3>Importer</h3>
            <fieldset>
                <h4>Budsjett</h4>
                {#each data.actual.budgets as budget}
                    {@const id = `budget-${budget.id}`}
                    <input name="budget" {id} value={budget.id} type="radio" bind:group={form.budgetId} />
                    <label for={id}>{budget.name}({budget.id})</label><br />
                {/each}
                <h4>Kontoer</h4>
                {#each data.sb1.accounts as account}
                    {@const actualId = `mapping-${account.key}-actual`}
                    <div>
                        <code>{account.name}</code>
                        <span>&#8594;</span>
                        <label for={actualId}>Actual</label>
                        <select name={actualId} id={actualId} onchange={(e) => onMappingChanged(account.key, e.currentTarget.value)}>
                            <option value="-" selected>-</option>
                            {#each data.actual.accounts as actual}
                                <option value={actual.id}>
                                    {actual.name}
                                </option>
                            {/each}
                        </select>
                    </div>
                {/each}
                <h4>Ellers</h4>
                <input type="checkbox" id="dry" bind:checked={form.dryRun} /><label for="dry">Tørrkjøring</label><br /><br />
                <input type="submit" />
            </fieldset>
        </form>
        <h3>Annet</h3>
        <Button onclick={logout} loading={navigating}>Logg ut</Button>
    {:else}
        <Button onclick={authorize} loading={navigating}>Autentisér hos Sparebanken 1</Button>
    {/if}
</main>
