use leptos::*;
use leptos_router::*;

use super::auth_base::AuthBase;

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

    let app = use_context::<AppService>().unwrap();
    let flashbag = use_context::<FlashBag>().unwrap();

    if password != confirm_password {
        return Err("Passwords don't match".to_string().into());
    }

    let password = Password::new(&password).map_err(|e| format!("{}", e))?;

    app.reset_password(&token.into(), &password).await.map_err(|e| format!("{}", e))?;

    let flash = FlashMessage::new("login",
        "Your password has been reset.".to_string()).with_alert(Alert::Success);

    flashbag.set(flash);

    leptos_axum::redirect("/auth/login");

    Ok(())
}

/// Renders the home page of your application.
#[component]
pub fn ResetPage() -> impl IntoView {
    let submit = Action::<ResetAction, _>::server();
    let response = submit.value().read_only();

    let params = use_params_map();

    let token = move || {
        params.with(|params| params.get("token").cloned())
    };

    let user = create_resource(token, move |_| async move {
        crate::domain::leptos::check_forgot_password_token(token()).await.unwrap()
    });

    view! {
            <AuthBase>

                <Suspense>
                    <Show when=move || response.get().is_some_and(|e| e.is_err())>
                        <div role="alert" class="alert alert-error my-2">
                            <i class="fas fa-exclamation-circle"></i>
                            <span>
                            { move || if let Some(Err(e)) = response.get() {
                                {format!("{}", e)}.into_view()
                            } else {
                                ().into_view()
                            }}
                            </span>
                        </div>
                    </Show>
                </Suspense>

                <ActionForm action=submit class="w-full">
                    <div class="flex flex-col gap-2">

                        <Suspense>
                            <Show when=move || user().is_some_and(|e| e.is_none())>
                                <Redirect path="/auth/login"/>
                            </Show>
                            <Show when=move || user().is_some_and(|e| e.is_some())>
                                <label class="input input-bordered flex items-center gap-2">
                                    <i class="fas fa-envelope"></i>
                                    <input type="text" class="grow" value={user().unwrap().unwrap().email().to_string()} disabled />
                                </label>
                            </Show>
                        </Suspense>

                        <label class="input input-bordered flex items-center gap-2">
                            <i class="fas fa-lock"></i>
                            <input type="password" placeholder="New Password" name="password" class="grow" />
                        </label>

                        <label class="input input-bordered flex items-center gap-2">
                            <i class="fas fa-lock"></i>
                            <input type="password" placeholder="Confirm Password" name="confirm_password" class="grow" />
                        </label>

                        <div>
                            <input type="hidden" name="token" value={token()} />
                            <input type="submit" value="Reset!" class="btn btn-primary btn-block" />
                        </div>

                        <div class="text-center text-sm">
                            "Remembered your password? Login "<a href="/auth/login" class="link">"here"</a>"!"
                        </div>
                    </div>
                    
                </ActionForm>

            </AuthBase>

    }
    .into_view()
}
