import { useEffect } from "react";
import { Outlet, useNavigate } from "react-router-dom";
import { client } from "../client";
import { useStore } from "../store";
import { Button } from "../styled/Button";
import { timeout } from "../utils";

export function Root() {

	const navigate = useNavigate();

	const user = useStore(state => state.user);
	const setUser = useStore(state => state.setUser);

	const init = async () => {
		if (user !== null) return;

		const { data, error } = await client.me.get();
		await timeout(1000);

		if (error !== null) {
			navigate("/login");
			return;
		}

		setUser(data);
	};

	useEffect(() => { init(); }, []);

	const onLogoutClick = async () => {
		const { error } = await client.logout.post();

		if (error !== null) {
			console.error("Response was not ok");
		}

		setUser(null);
		navigate("/login");
	};

	if (user === null) {
		return (
			<div className="w-full h-full overflow-hidden flex items-center justify-center">
				<div>Ładowanie…</div>
			</div>
		);
	}

	return (
		<div className="w-full h-full overflow-hidden flex flex-col items-stretch">
			<div className="flex p-4 justify-between items-baseline">
				<div>
					Użytkownik: {user.username} (<span className="font-mono text-sm">{user.userId}</span>)
				</div>
				<div>
					<Button type="button" onClick={onLogoutClick}>
						Wyloguj się
					</Button>
				</div>
			</div>
			<Outlet context={user} />
		</div>
	);
}
