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

use super::auth_base::AuthBase;

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

    let email = EmailAddress::new(&email).map_err(|_| format!("\"{}\" is not a email address", email))?;

    let app = use_context::<AppService>().unwrap();
    let flashbag = use_context::<FlashBag>().unwrap();
    
    // If the email address is known, we'll set a recovery link, if it's not, we wont, but the flash remains the same.
    app.forgot_password(&email).await;

    let flash = FlashMessage::new("login",
        format!(
            "An e-mail has been sent to {} with a link to reset your password.",
            email
        )).with_alert(Alert::Success);

    flashbag.set(flash);

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

    Ok(())
}

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

    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">
                        <label class="input input-bordered flex items-center gap-2">
                            <i class="fas fa-envelope"></i>
                            <input type="text" placeholder="E-mail" name="email" class="grow" />
                        </label>

                        <div>
                            <input type="submit" value="Request Password Reset" class="btn btn-primary btn-block" />
                        </div>

                        <div class="text-center text-sm">
                            "New Account? Sign up "<a href="/auth/register" class="link">"here"</a>"!"
                        </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()
}
