//! 登录页面
//!
//! 提供用户名/密码表单，前端校验通过后调用 `login` server function，
//! 登录成功时跳转到管理后台首页。

use dioxus::prelude::*;
use dioxus::router::components::Link;

use crate::api::auth::{login, AuthResponse};
use crate::components::forms::{AlertBox, FormInput, FormLabel, BUTTON_PRIMARY_CLASS};
use crate::context::UserContext;
use crate::router::Route;

/// 登录页面组件
#[component]
pub fn Login() -> Element {
    // 表单输入状态
    let mut username = use_signal(|| "".to_string());
    let mut password = use_signal(|| "".to_string());
    // 错误提示与加载状态
    let mut error = use_signal(|| None::<String>);
    let mut loading = use_signal(|| false);
    // 全局用户上下文，用于触发登录后的状态刷新
    let mut ctx: UserContext = use_context();

    // 提交登录表单
    let on_submit = Callback::new(move |_| {
        if loading() {
            return;
        }
        error.set(None);
        loading.set(true);

        let username_val = username();
        let password_val = password();

        // 在异步任务中调用 server function 登录
        spawn(async move {
            match login(username_val, password_val).await {
                Ok(AuthResponse { success: true, .. }) => {
                    // 登录成功：重置上下文检查标记并跳转到后台
                    ctx.checked.set(false);
                    let _ = dioxus::router::navigator().push(Route::Admin {});
                }
                Ok(AuthResponse {
                    success: false,
                    message,
                    ..
                }) => {
                    error.set(Some(message));
                }
                Err(e) => {
                    error.set(Some(format!("请求失败: {}", e)));
                }
            }
            loading.set(false);
        });
    });

    let is_loading = loading();

    rsx! {
        div { class: "min-h-screen flex items-center justify-center bg-paper-theme",
            div { class: "w-full max-w-md p-8 bg-paper-entry rounded-2xl border border-paper-border shadow-sm",
                h1 { class: "text-2xl font-bold text-center text-paper-primary mb-6",
                    "登录"
                }

                if let Some(err) = error() {
                    AlertBox { message: err, variant: "error" }
                }

                div { class: "space-y-4",
                    div {
                        FormLabel {
                            label: "用户名 / 邮箱",
                            html_for: Some("login-username".to_string()),
                        }
                        FormInput {
                            id: Some("login-username".to_string()),
                            r#type: "text",
                            placeholder: "用户名或邮箱",
                            value: username(),
                            disabled: is_loading,
                            oninput: move |v: String| username.set(v),
                            // 回车键触发提交
                            onkeydown: Some(
                                EventHandler::new(move |e: KeyboardEvent| {
                                    if e.key() == Key::Enter {
                                        on_submit(())
                                    }
                                }),
                            ),
                        }
                    }
                    div {
                        FormLabel {
                            label: "密码",
                            html_for: Some("login-password".to_string()),
                        }
                        FormInput {
                            id: Some("login-password".to_string()),
                            r#type: "password",
                            placeholder: "密码",
                            value: password(),
                            disabled: is_loading,
                            oninput: move |v: String| password.set(v),
                            onkeydown: Some(
                                EventHandler::new(move |e: KeyboardEvent| {
                                    if e.key() == Key::Enter {
                                        on_submit(())
                                    }
                                }),
                            ),
                        }
                    }
                    button {
                        class: "{BUTTON_PRIMARY_CLASS}",
                        class: if is_loading { "opacity-60 cursor-not-allowed" },
                        disabled: is_loading,
                        onclick: move |_| on_submit(()),
                        if is_loading {
                            "登录中..."
                        } else {
                            "登录"
                        }
                    }
                    Link {
                        class: "block w-full py-2 px-4 text-center text-paper-secondary hover:text-paper-accent font-medium rounded-lg transition-all duration-200 cursor-pointer",
                        to: Route::Register {},
                        "还没有账号？去注册"
                    }
                }
            }
        }
    }
}
