use leptos::*;
use leptos_router::{use_query_map, Redirect};

use crate::domain::api::prelude::User;

#[server]
async fn logout_action() -> Result<(), ServerFnError<String>> {
    use crate::domain::api::prelude::*;

    let session = use_context::<Session>().unwrap();
    session.clear();

    Ok(())
}

#[component]
pub fn LogoutPage(
    trigger_signal: RwSignal<bool>,
    user_signal: RwSignal<Option<User>>,
) -> impl IntoView {
    let direct_signal = create_rw_signal(None::<String>);

    create_local_resource(
        || (),
        move |_| async move {
            logout_action().await.unwrap();
            trigger_signal.set(!trigger_signal.get_untracked());

            let query = use_query_map();
            if let Some(c) = query.with_untracked(|q| q.get("c").cloned()) {
                direct_signal.set(Some(c));
            } else {
                direct_signal.set(Some("Lw".to_string()));
            }
        },
    );

    view! {
        <Suspense>
            <Show when=move || (direct_signal().is_some() && user_signal().is_none())>
                <Redirect path={ format!("/auth/login?c={}", direct_signal().unwrap()) } />
            </Show>
        </Suspense>
    }
}
