import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { client } from "../client";
import { useStore } from "../store";

export const Home = () => {

	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();

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

		setUser(data);
	};

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

	const onLogoutClick = async () => {
		const { data, 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-[1000px] max-w-full mx-auto flex flex-col items-stretch">
				<div className="p-2 text-center">Ładowanie…</div>
			</div>
		);
	}

	return (
		<div className="w-[1000px] max-w-full mx-auto flex flex-col items-stretch">
			<div className="p-2 flex justify-between items-baseline">
				<div>
					Użytkownik: {user.username}
				</div>
				<div>
					<button
						className="p-2 bg-stone-300 border-2 border-t-stone-200 border-l-stone-200 border-r-stone-600 border-b-stone-600 rounded"
						type="button"
						onClick={onLogoutClick}
					>
						Wyloguj się
					</button>
				</div>
			</div>
		</div>
	);
};
