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 { postCode, postDemoLogin, 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 (email.toString() === "demo@email.com") {
            const { access, refresh } = await postDemoLogin();

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

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

        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 (
        <Show when={!isAuthorized} fallback={<Navigate href="/" />}>
            <form
                ref={form}
                onSubmit={onSubmit}
                class="flex flex-col gap-2 mt-4 w-72"
            >
                <TextField name="email" class="flex flex-col gap-4">
                    <TextField.Label class="text-xl font-semibold">
                        Email
                    </TextField.Label>
                    <TextField.Input
                        pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
                        type="email"
                        class="rounded px-1 py-2"
                    />
                </TextField>
                <Show when={submitted()}>
                    <TextField name="code" class="flex flex-col gap-2">
                        <TextField.Label class="text-xl font-semibold">
                            Code
                        </TextField.Label>
                        <TextField.Input class="rounded px-1 py-2" />
                    </TextField>
                </Show>
                <Button
                    type="submit"
                    class="rounded-xl bg-slate-800 px-2 py-4 text-neutral-200"
                >
                    Submit
                </Button>
            </form>
        </Show>
    );
};
