//! Create new user page component.

use leptos::prelude::*;
#[cfg(feature = "hydrate")]
use leptos::task::spawn_local;

use crate::components::{Card, MessageAlert, PageHeader, TempPasswordDisplay};

/// User new page component.
#[component]
pub fn UserNewPage() -> impl IntoView {
    let (username, set_username) = signal(String::new());
    let (email, set_email) = signal(String::new());
    let (display_name, set_display_name) = signal(String::new());
    let (message, set_message) = signal(Option::<(String, bool)>::None);
    let (pending, set_pending) = signal(false);
    let (temp_password, _set_temp_password) = signal(Option::<String>::None);
    #[cfg(feature = "hydrate")]
    let set_temp_password = _set_temp_password;

    let on_submit = move |ev: leptos::ev::SubmitEvent| {
        ev.prevent_default();
        set_pending.set(true);
        set_message.set(None);

        #[cfg(feature = "hydrate")]
        {
            use gloo_net::http::Request;

            let data = serde_json::json!({
                "username": username.get(),
                "email": if email.get().is_empty() { None::<String> } else { Some(email.get()) },
                "display_name": display_name.get()
            });

            spawn_local(async move {
                let response = Request::post("/api/admin/users")
                    .json(&data)
                    .unwrap()
                    .send()
                    .await;

                set_pending.set(false);

                match response {
                    Ok(resp) if resp.ok() => {
                        #[derive(serde::Deserialize)]
                        struct CreateResponse {
                            temporary_password: String,
                        }
                        if let Ok(result) = resp.json::<CreateResponse>().await {
                            set_temp_password.set(Some(result.temporary_password));
                            set_message.set(Some(("User created successfully!".to_string(), true)));
                            set_username.set(String::new());
                            set_email.set(String::new());
                            set_display_name.set(String::new());
                        }
                    }
                    Ok(resp) => {
                        #[derive(serde::Deserialize)]
                        struct ErrorResp {
                            error: String,
                        }
                        if let Ok(err) = resp.json::<ErrorResp>().await {
                            set_message.set(Some((err.error, false)));
                        } else {
                            set_message.set(Some(("Failed to create user".to_string(), false)));
                        }
                    }
                    Err(_) => {
                        set_message.set(Some(("Network error".to_string(), false)));
                    }
                }
            });
        }
    };

    view! {
        <PageHeader title="Create New User" subtitle="Add a new user account">
            <a href="/admin/users" class="btn btn-secondary">"Back to Users"</a>
        </PageHeader>

        <Card>
            <form on:submit=on_submit>
                <div class="form-row">
                    <div class="form-group">
                        <label for="username" class="form-label">
                            "Username" <span class="required">"*"</span>
                        </label>
                        <input
                            type="text"
                            id="username"
                            required=true
                            minlength=3
                            maxlength=32
                            pattern="[a-zA-Z][a-zA-Z0-9_]*"
                            class="form-input"
                            placeholder="username"
                            prop:value=move || username.get()
                            on:input=move |ev| set_username.set(event_target_value(&ev))
                        />
                        <small class="form-help">"Letters, numbers, and underscores only"</small>
                    </div>
                    <div class="form-group">
                        <label for="email" class="form-label">"Email"</label>
                        <input
                            type="email"
                            id="email"
                            class="form-input"
                            placeholder="user@example.com"
                            prop:value=move || email.get()
                            on:input=move |ev| set_email.set(event_target_value(&ev))
                        />
                    </div>
                </div>

                <div class="form-group">
                    <label for="display_name" class="form-label">
                        "Display Name" <span class="required">"*"</span>
                    </label>
                    <input
                        type="text"
                        id="display_name"
                        required=true
                        minlength=1
                        maxlength=64
                        class="form-input"
                        placeholder="Display Name"
                        prop:value=move || display_name.get()
                        on:input=move |ev| set_display_name.set(event_target_value(&ev))
                    />
                </div>

                <MessageAlert message=message />
                <TempPasswordDisplay password=temp_password />

                <div class="form-actions">
                    <button
                        type="submit"
                        class="btn btn-primary"
                        disabled=move || pending.get()
                    >
                        {move || if pending.get() { "Creating..." } else { "Create User" }}
                    </button>
                </div>
            </form>
        </Card>
    }
}
