pub mod auth;
pub mod icons;
pub mod navbar;
pub mod topbar;

use crate::{
    util::model::{session::Session, user::User},
    Route,
};
use auth::Auth;
use dioxus::prelude::*;

#[component]
pub fn Global() -> Element {
    let user = use_resource(get_user_from_cookie);
    let mut user_state: Signal<Option<User>> = use_signal(|| None);

    use_context_provider(|| user_state);

    use_effect(move || {
        if let Some(Ok(u)) = &*user.read_unchecked() {
            user_state.set(Some(u.clone()));
        };
    });

    rsx! {
        match &*user.read_unchecked() {
            Some(Ok(_)) => rsx! {
                if user_state().is_some() {
                    crate::components::layout::topbar::Topbar {}
                    main {
                        class: "h-full overflow-y-auto flex justify-center px-2 py-5",
                        Outlet::<Route> {}
                    }
                    crate::components::layout::navbar::Navbar {}
                }
            },
            Some(Err(_)) => rsx! {
                Auth { }
            },
            None => rsx! {
                div { "Loading..." }
            }
        }
    }
}

#[server]
async fn get_user_from_cookie() -> Result<User, ServerFnError> {
    let user = Session::fetch_current_user().await?;

    Ok(user)
}
