import { Button } from "@kobalte/core/button";
import { TextField } from "@kobalte/core/text-field";
import { Navigate } from "@solidjs/router";
import { type Component, Show, createSignal } from "solid-js";
import { isTokenValid } from "./ProtectedRoute";
import { base, postCode, postLogin } from "./network";

export const Login: Component = () => {
    let form: HTMLFormElement | undefined;

    const [submitted, setSubmitted] = createSignal(false);

    const onSubmit: HTMLFormElement["onsubmit"] = async (e) => {
        e.preventDefault();
        const formData = new FormData(form);
        const email = formData.get("email");
        if (email == null) {
            throw new Error("bruh, no email");
        }

        if (!submitted()) {
            await postLogin(email.toString());
            setSubmitted(true);
        } else {
            const code = formData.get("code");
            if (code == null) {
                throw new Error("bruh, no code");
            }

            const { access, refresh } = await postCode(
                email.toString(),
                code.toString(),
            );

            localStorage.setItem("access", access);
            localStorage.setItem("refresh", refresh);

            window.location.href = "/";
        }
    };

    const isAuthorized = isTokenValid();

    return (
        <>
            {base}
            <Show when={!isAuthorized} fallback={<Navigate href="/" />}>
                <form ref={form} onSubmit={onSubmit}>
                    <TextField name="email">
                        <TextField.Label>Email</TextField.Label>
                        <TextField.Input />
                    </TextField>
                    <Show when={submitted()}>
                        <TextField name="code">
                            <TextField.Label>Code</TextField.Label>
                            <TextField.Input />
                        </TextField>
                    </Show>
                    <Button type="submit">Submit</Button>
                </form>
            </Show>
        </>
    );
};
