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

use super::server_fns::server_accept_gdpr;

/// Third step of the OTP login flow for new accounts: GDPR consent collection.
#[component]
pub fn GdprStep(
    pending_token: String,
    on_success: Callback<UserInfo>,
    error_msg: RwSignal<Option<String>>,
) -> impl IntoView {
    let lang = use_current_language();
    let loading = RwSignal::new(false);
    let accept_required = RwSignal::new(false);
    let accept_marketing = RwSignal::new(false);

    let title = Memo::new(move |_| UnifiedI18n::new(&lang.get(), "/").t("auth-gdpr-title"));
    let description =
        Memo::new(move |_| UnifiedI18n::new(&lang.get(), "/").t("auth-gdpr-description"));
    let required_label =
        Memo::new(move |_| UnifiedI18n::new(&lang.get(), "/").t("auth-gdpr-accept-required"));
    let marketing_label =
        Memo::new(move |_| UnifiedI18n::new(&lang.get(), "/").t("auth-gdpr-accept-marketing"));
    let submit_label = Memo::new(move |_| UnifiedI18n::new(&lang.get(), "/").t("auth-gdpr-submit"));

    let token = pending_token.clone();

    let submit = move |ev: leptos::ev::SubmitEvent| {
        ev.prevent_default();

        if !accept_required.get() {
            return;
        }

        let t = token.clone();
        loading.set(true);
        error_msg.set(None);

        spawn_local(async move {
            match server_accept_gdpr(t).await {
                Ok(user_info) => on_success.run(user_info),
                Err(err) => error_msg.set(Some(err.to_string())),
            }
            loading.set(false);
        });
    };

    view! {
        <form on:submit=submit 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">{description}</p>

            <label class="flex items-start gap-3 cursor-pointer">
                <input
                    type="checkbox"
                    id="gdpr-accept-required"
                    name="gdpr_required"
                    class="w-4 h-4 mt-1 shrink-0 cursor-pointer rounded"
                    style="accent-color: hsl(var(--p));"
                    prop:checked=accept_required
                    on:change=move |ev| accept_required.set(event_target_checked(&ev))
                />
                <span class="text-sm text-base-content" inner_html=required_label />
            </label>

            <label class="flex items-start gap-3 cursor-pointer">
                <input
                    type="checkbox"
                    id="gdpr-accept-marketing"
                    name="gdpr_marketing"
                    class="w-4 h-4 mt-1 shrink-0 cursor-pointer rounded"
                    style="accent-color: hsl(var(--p));"
                    prop:checked=accept_marketing
                    on:change=move |ev| accept_marketing.set(event_target_checked(&ev))
                />
                <span class="text-sm text-base-content/70">{marketing_label}</span>
            </label>

            <button
                type="submit"
                class="btn btn-primary w-full"
                prop:disabled=move || loading.get() || !accept_required.get()
            >
                {move || if loading.get() { "…".to_string() } else { submit_label.get() }}
            </button>

            {move || error_msg.get().map(|e| view! {
                <p class="text-error text-sm">{e}</p>
            })}
        </form>
    }
}
