use crate::codec::ron::Ron;
use crate::pages;
use leptos::prelude::*;
use leptos_router::components::*;
use leptos_router::path;

pub fn shell(options: LeptosOptions) -> impl IntoView {
    use leptos_meta::MetaTags;

    view! {
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="utf-8" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <AutoReload options=options.clone() />
                <HydrationScripts options />
                <MetaTags />
            </head>
            <body class="text-white bg-slate-950">
                <App />
            </body>
        </html>
    }
}

#[component]
pub fn App() -> impl IntoView {
    use leptos_meta::Stylesheet;
    use leptos_meta::Title;

    tracing::debug!("Rendering root component");

    // Provides context that manages stylesheets, titles, meta tags, etc.
    leptos_meta::provide_meta_context();

    leptos::view! {
        <Stylesheet id="leptos" href="/pkg/ascend.css" />

        <Title text="Ascend" />

        <Router>
            <Routes fallback=|| "Not found">
                <Route path=path!("/") view=Home />
                <Route path=path!("/wall/:wall_uid") view=pages::wall::Wall />
                <Route path=path!("/wall/:wall_uid/edit") view=pages::edit_wall::EditWall />
                <Route path=path!("/wall/:wall_uid/routes") view=pages::routes::Routes />
            </Routes>
        </Router>
    }
}

#[component]
pub fn Home() -> impl IntoView {
    // TODO: show cards with walls, and a "new wall" button

    tracing::debug!("Rendering home component");

    // dbg!(leptos::prelude::Owner::current().map(|o| o.ancestry()));

    let wall_uid = OnceResource::<_, Ron>::new_with_options(
        async move {
            // dbg!(leptos::prelude::Owner::current().map(|o| o.ancestry()));
            let walls = crate::server_functions::get_walls()
                .await
                .inspect_err(|e| {
                    dbg!(e);
                })
                .expect("failed to get walls")
                .into_inner();
            walls.first().map(|wall| wall.uid)
        },
        false,
    );

    Effect::new(move || {
        tracing::debug!("running effect");

        if let Some(wall_uid) = wall_uid.get().flatten() {
            tracing::debug!("navigating");
            let navigate = leptos_router::hooks::use_navigate();
            let url = format!("/wall/{}", wall_uid);
            navigate(&url, Default::default());
            tracing::debug!("navigated");
        }
    });
}
