use leptos::prelude::*;
use leptos::task::spawn_local;
use rustelo_core_lib::{i18n::UnifiedI18n, state::use_current_language};

use super::server_fns::server_request_otp;

/// First step of the OTP login flow: collect the user's email address.
#[component]
pub fn EmailStep(
    on_success: Callback<String>,
    error_msg: RwSignal<Option<String>>,
) -> impl IntoView {
    let lang = use_current_language();
    let email = RwSignal::new(String::new());
    let loading = RwSignal::new(false);

    let title = Memo::new(move |_| UnifiedI18n::new(&lang.get(), "/").t("auth-otp-modal-title"));
    let subtitle =
        Memo::new(move |_| UnifiedI18n::new(&lang.get(), "/").t("auth-otp-modal-subtitle"));
    let continue_label =
        Memo::new(move |_| UnifiedI18n::new(&lang.get(), "/").t("auth-otp-continue"));

    let submit = move |ev: leptos::ev::SubmitEvent| {
        ev.prevent_default();
        let current_email = email.get();
        let current_lang = {
            #[cfg(target_arch = "wasm32")]
            {
                lang.get()
            }
            #[cfg(not(target_arch = "wasm32"))]
            {
                lang.get_untracked()
            }
        };
        loading.set(true);
        error_msg.set(None);
        spawn_local(async move {
            match server_request_otp(current_email.clone(), current_lang).await {
                Ok(()) => on_success.run(current_email),
                Err(e) => error_msg.set(Some(e.to_string())),
            }
            loading.set(false);
        });
    };

    view! {
        <form on:submit=submit novalidate class="flex flex-col gap-4">
            <h2 class="text-xl font-semibold text-base-content">{title}</h2>
            <p class="text-sm text-base-content/70">{subtitle}</p>
            <input
                type="email"
                id="auth-email"
                name="email"
                autocomplete="email"
                aria-label="Email address"
                placeholder="you@example.com"
                required
                class="input input-bordered w-full"
                prop:value=email
                on:input=move |ev| email.set(event_target_value(&ev))
            />
            <button
                type="submit"
                class="btn btn-primary w-full"
                prop:disabled=loading
            >
                {move || if loading.get() { "…".to_string() } else { continue_label.get() }}
            </button>
            {move || error_msg.get().map(|e| view! {
                <p class="text-error text-sm">{e}</p>
            })}
        </form>
    }
}
