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


use super::auth_base::AuthBase;



#[server]
async fn register_action(
    email: 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 email = EmailAddress::new(&email).map_err(|_| format!("\"{}\" is not a email address", email))?;
    let password = Password::new(&password).map_err(|e| format!("{}", e))?;

    let user = app.create_user(CreateUserRequest::new(email, password))
        .await
        .map_err(|e| format!("{}", e))?;

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

    flashbag.set(flash);

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

    Ok(())
}

/// Renders the home page of your application.
#[component]
pub fn RegisterPage() -> impl IntoView {
    let submit = Action::<RegisterAction, _>::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>

                    <label class="input input-bordered flex items-center gap-2">
                        <i class="fas fa-lock"></i>
                        <input type="password" placeholder="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="submit" value="Sign Up!" class="btn btn-primary btn-block" />
                    </div>

                    <div class="text-center text-sm">
                        "Already have an Account? Login "<a href="/auth/login" class="link">"here"</a>"!"
                    </div>
                </div>
                
            </ActionForm>
        </AuthBase>
    }.into_view()
}
