<svelte:options runes={true} />

<script lang="ts">
    import { Input } from "$lib/components/ui/input";
    import * as Form from "$lib/components/ui/form";
    import { formSchema, type FormSchema } from "./schema";
    import {OpenSubsonic} from "$lib/opensubsonic";
    import {
        type SuperValidated,
        type Infer,
        superForm,
    } from "sveltekit-superforms";
    import { zodClient } from "sveltekit-superforms/adapters";
    import Cookies from 'js-cookie'
    import {goto} from "$app/navigation";
    import LoadingSpinner from "$lib/components/custom/LoadingSpinner.svelte";

    let  { data }: SuperValidated<Infer<FormSchema>> = $props<{ data: SuperValidated<Infer<FormSchema>> }>();

    const form = superForm(data, {
        validators: zodClient(formSchema),
        onUpdated() {
            OpenSubsonic.username = previousForm.get("username");
            OpenSubsonic.password = previousForm.get("password");
            OpenSubsonic.get("ping").then((data) => {
                if (data) {
                    if (data.status === "ok") {
                        OpenSubsonic.storeCredentials();
                        loading = false;
                        let route = Cookies.get("preLoginRoute")
                        Cookies.remove("preLoginRoute", { path: "/login" })
                        goto(route);
                    }
                    else {
                        error = true;
                        loading = false;
                    }
                }
                else {
                    error = true;
                    loading = false;
                }
            });
        },
        onSubmit({ formData }) {
            loading = true;
            previousForm = formData;
        }
    });
    let previousForm: FormData = $state({});

    const { form: formData, enhance } = form;

    let error = $state(false);
    let loading = $state(false);
</script>

<form method="POST" use:enhance>
    <Form.Field {form} name="username" class="px-3">
        <Form.Control let:attrs>
            <Form.Label>Username:</Form.Label>
            <Input {...attrs} bind:value={$formData.username}></Input>
        </Form.Control>
        <Form.FieldErrors></Form.FieldErrors>
    </Form.Field>
    <Form.Field {form} name="password" class="px-3">
        <Form.Control let:attrs>
            <Form.Label>Password:</Form.Label>
            <Input {...attrs} type="password" bind:value={$formData.password}></Input>
        </Form.Control>
        <Form.FieldErrors></Form.FieldErrors>
    </Form.Field>
    <div class="flex flex-row justify-center pt-2">
        {#if loading}
            <LoadingSpinner />
        {:else}
            <Form.Button>Login</Form.Button>
        {/if}
    </div>
    {#if error}
    <p class="pt-2 text-sm text-destructive">Username or Password incorrect</p>
    {/if}
</form>