import { Match, Switch, createSignal, onMount } from "solid-js";

type ConnectionStatus = "connected" | "connecting" | "disconnected" | "error";
export function ClassroomConection() {
    const [status, setStatus] = createSignal<ConnectionStatus>("disconnected");

    const connectToRemote = () => {
        setStatus("connecting");

        fetch(`${import.meta.env.VITE_BACKEND_URL}/api/classroom/connect`)
            .then((response) => {
                if (response.ok) {
                    setStatus("connected");
                } else {
                    response.json().then((json) => {
                        console.error(json);
                        setStatus("error");
                    });
                }
            })
            .catch((err) => {
                console.error(err);
                setStatus("error");
            });

        // setTimeout(() => setStatus("disconnected"), 5000);
    };

    onMount(connectToRemote);

    return (
        <div class="bg-c-surface-variant text-c-on-surface-variant rounded-md p-2 mt-4">
            Conexión al aula virtual:&nbsp;
            <Switch fallback={"Desconectado"}>
                <Match when={status() === "connected"}>
                    <span class="bg-c-success text-c-on-success px-2 rounded select-none font-mono">
                        Ok
                    </span>
                </Match>
                <Match when={status() === "connecting"}>
                    <span
                        class="px-2 rounded select-none font-mono
                        bg-[var(--c-orange-primary)] text-[var(--c-orange-on-primary)]"
                    >
                        Conectando...
                    </span>
                </Match>
                <Match when={status() === "error"}>
                    <span class="bg-c-error text-c-on-error px-2 rounded font-mono">
                        Error
                    </span>
                </Match>
                <Match when={status() === "disconnected"}>
                    <span class="bg-c-error-container text-c-on-error-container px-2 rounded font-mono">
                        Desconectado
                    </span>
                </Match>
            </Switch>
        </div>
    );
}
