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

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

    if ident.len() > 10 {
        return Err(ServerFnError::WrappedServerError(
            "ATC_ID exceeding 10 characters".into(),
        ));
    }

    let Some(user) = check_user().await? else {
        return Err(ServerFnError::WrappedServerError("No user".into()));
    };

    let app = use_context::<AppService>().unwrap();

    app.send(&user, Packets::SimConnect(SimConnectPacket::AtcID(ident)))
        .await
        .map_err(|e| format!("{:#?}", e))?;

    Ok(())
}

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

    view! {
        <div class="p-10">
            <pre>Hello, { user.email().to_string() }!</pre>
            <div class="content has-text-centered link">
                <a href="/auth/logout">Logout</a>
            </div>
            <div>
                <ActionForm action=submit>
                <label class="input input-bordered flex items-center gap-2">
                    <i class="fas fa-envelope"></i>
                    <input type="text" placeholder="Registration Number" maxlength="10" name="ident" />
                </label>
                <div>
                    <input type="submit" value="Update" class="btn btn-block" />
                </div>
                </ActionForm>
            </div>
        </div>
    }
    .into_view()
}
