//! Create new server avatar page component.

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

use crate::components::{Card, PageHeader};
use crate::utils::name_to_slug;

/// Server avatar new page component.
#[component]
pub fn AvatarsNewPage() -> impl IntoView {
    // Form state
    let (name, set_name) = signal(String::new());
    let (slug, set_slug) = signal(String::new());
    let (description, set_description) = signal(String::new());
    let (is_public, set_is_public) = signal(true);
    let (thumbnail_path, set_thumbnail_path) = signal(String::new());

    // UI state
    let (message, set_message) = signal(Option::<(String, bool)>::None);
    let (pending, set_pending) = signal(false);
    let (created_id, _set_created_id) = signal(Option::<String>::None);
    #[cfg(feature = "hydrate")]
    let set_created_id = _set_created_id;
    let (slug_auto, set_slug_auto) = signal(true);

    let update_name = move |ev: leptos::ev::Event| {
        let new_name = event_target_value(&ev);
        set_name.set(new_name.clone());
        if slug_auto.get() {
            set_slug.set(name_to_slug(&new_name));
        }
    };

    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!({
                "name": name.get(),
                "slug": if slug.get().is_empty() { None::<String> } else { Some(slug.get()) },
                "description": if description.get().is_empty() { None::<String> } else { Some(description.get()) },
                "is_public": is_public.get(),
                "thumbnail_path": if thumbnail_path.get().is_empty() { None::<String> } else { Some(thumbnail_path.get()) }
            });

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

                set_pending.set(false);

                match response {
                    Ok(resp) if resp.ok() => {
                        #[derive(serde::Deserialize)]
                        struct CreateResponse {
                            id: String,
                            #[allow(dead_code)]
                            name: String,
                            #[allow(dead_code)]
                            slug: String,
                        }
                        if let Ok(result) = resp.json::<CreateResponse>().await {
                            set_created_id.set(Some(result.id));
                            set_message.set(Some(("Avatar created successfully!".to_string(), true)));
                        }
                    }
                    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 avatar".to_string(), false)));
                        }
                    }
                    Err(_) => {
                        set_message.set(Some(("Network error".to_string(), false)));
                    }
                }
            });
        }
    };

    view! {
        <PageHeader title="Create Server Avatar" subtitle="Add a new pre-configured avatar template">
            <a href="/admin/avatars" class="btn btn-secondary">"Back to Avatars"</a>
        </PageHeader>

        <Card>
            <form on:submit=on_submit>
                <h3 class="section-title">"Avatar Details"</h3>

                <div class="form-row">
                    <div class="form-group">
                        <label for="name" class="form-label">
                            "Name" <span class="required">"*"</span>
                        </label>
                        <input
                            type="text"
                            id="name"
                            required=true
                            class="form-input"
                            placeholder="Happy Robot"
                            prop:value=move || name.get()
                            on:input=update_name
                        />
                    </div>
                    <div class="form-group">
                        <label for="slug" class="form-label">"Slug (URL)"</label>
                        <input
                            type="text"
                            id="slug"
                            pattern="[a-z0-9][a-z0-9\\-]*[a-z0-9]|[a-z0-9]"
                            class="form-input"
                            placeholder="happy-robot"
                            prop:value=move || slug.get()
                            on:input=move |ev| {
                                set_slug_auto.set(false);
                                set_slug.set(event_target_value(&ev));
                            }
                        />
                        <small class="form-help">"Optional. Auto-generated from name if not provided."</small>
                    </div>
                </div>

                <div class="form-group">
                    <label for="description" class="form-label">"Description"</label>
                    <textarea
                        id="description"
                        class="form-textarea"
                        placeholder="A cheerful robot avatar for friendly chats"
                        prop:value=move || description.get()
                        on:input=move |ev| set_description.set(event_target_value(&ev))
                    ></textarea>
                </div>

                <div class="form-group">
                    <label for="thumbnail_path" class="form-label">"Thumbnail Path"</label>
                    <input
                        type="text"
                        id="thumbnail_path"
                        class="form-input"
                        placeholder="avatars/thumbnails/happy-robot.png"
                        prop:value=move || thumbnail_path.get()
                        on:input=move |ev| set_thumbnail_path.set(event_target_value(&ev))
                    />
                    <small class="form-help">"Relative path to thumbnail image in assets folder."</small>
                </div>

                <h3 class="section-title">"Visibility"</h3>

                <div class="checkbox-group">
                    <label class="checkbox-label">
                        <input
                            type="checkbox"
                            class="form-checkbox"
                            prop:checked=move || is_public.get()
                            on:change=move |ev| set_is_public.set(event_target_checked(&ev))
                        />
                        "Public"
                    </label>
                    <small class="form-help">"Public avatars can be selected by users. Private avatars are only available to admins."</small>
                </div>

                <Show when=move || message.get().is_some()>
                    {move || {
                        let (msg, is_success) = message.get().unwrap_or_default();
                        let class = if is_success { "alert alert-success" } else { "alert alert-error" };
                        view! {
                            <div class=class role="alert">
                                <p>{msg}</p>
                            </div>
                        }
                    }}
                </Show>

                <Show when=move || created_id.get().is_some()>
                    {move || {
                        let id = created_id.get().unwrap_or_default();
                        view! {
                            <div class="alert alert-info">
                                <p>
                                    <a href=format!("/admin/avatars/{}", id)>
                                        "View avatar"
                                    </a>
                                </p>
                            </div>
                        }
                    }}
                </Show>

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