//! Realm avatar detail/edit page component.

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

use crate::components::{Card, DeleteConfirmation, DetailGrid, DetailItem, MessageAlert, PageHeader};
use crate::hooks::use_fetch_if;
use crate::models::RealmAvatarDetail;
use crate::utils::get_api_base;

/// Realm avatar detail page component.
#[component]
pub fn RealmAvatarsDetailPage() -> impl IntoView {
    let params = use_params_map();
    let realm_slug = move || params.get().get("slug").unwrap_or_default();
    let avatar_id = move || params.get().get("avatar_id").unwrap_or_default();
    let initial_realm_slug = params.get_untracked().get("slug").unwrap_or_default();
    let initial_avatar_id = params.get_untracked().get("avatar_id").unwrap_or_default();

    let (message, set_message) = signal(Option::<(String, bool)>::None);

    let avatar = use_fetch_if::<RealmAvatarDetail>(
        move || !realm_slug().is_empty() && !avatar_id().is_empty(),
        move || format!("{}/realms/{}/avatars/{}", get_api_base(), realm_slug(), avatar_id()),
    );

    let realm_slug_for_back = initial_realm_slug.clone();

    view! {
        <PageHeader title="Realm Avatar Details" subtitle=format!("ID: {}", initial_avatar_id)>
            <a href=format!("/admin/realms/{}/avatars", realm_slug_for_back) class="btn btn-secondary">"Back to Avatars"</a>
        </PageHeader>

        <Suspense fallback=|| view! { <p>"Loading avatar..."</p> }>
            {move || {
                let realm_slug = initial_realm_slug.clone();
                avatar.get().map(move |maybe_avatar| {
                    match maybe_avatar {
                        Some(a) => view! {
                            <RealmAvatarDetailView
                                avatar=a
                                realm_slug=realm_slug.clone()
                                message=message
                                set_message=set_message
                            />
                        }.into_any(),
                        None => view! {
                            <Card>
                                <p class="text-error">"Avatar not found or you don't have permission to view."</p>
                            </Card>
                        }.into_any()
                    }
                })
            }}
        </Suspense>
    }
}

#[component]
#[allow(unused_variables)]
fn RealmAvatarDetailView(
    avatar: RealmAvatarDetail,
    realm_slug: String,
    message: ReadSignal<Option<(String, bool)>>,
    set_message: WriteSignal<Option<(String, bool)>>,
) -> impl IntoView {
    #[cfg(feature = "hydrate")]
    let avatar_id = avatar.id.clone();
    #[cfg(feature = "hydrate")]
    let realm_slug_for_api = realm_slug.clone();
    let realm_slug_for_delete = realm_slug.clone();
    let slug_display = avatar.slug.clone();
    let (pending, set_pending) = signal(false);
    let (delete_pending, set_delete_pending) = signal(false);

    // Form state
    let (name, set_name) = signal(avatar.name.clone());
    let (description, set_description) = signal(avatar.description.clone().unwrap_or_default());
    let (is_public, set_is_public) = signal(avatar.is_public);
    let (is_active, set_is_active) = signal(avatar.is_active);
    let (thumbnail_path, set_thumbnail_path) = signal(
        avatar.thumbnail_path.clone().unwrap_or_default(),
    );

    // Thumbnail preview
    let thumbnail_preview = move || {
        let path = thumbnail_path.get();
        if path.is_empty() {
            None
        } else {
            Some(format!("/assets/{}", path))
        }
    };

    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 api_base = get_api_base();
            let avatar_id = avatar_id.clone();
            let realm_slug = realm_slug_for_api.clone();
            let data = serde_json::json!({
                "name": name.get(),
                "description": if description.get().is_empty() { None::<String> } else { Some(description.get()) },
                "is_public": is_public.get(),
                "is_active": is_active.get(),
                "thumbnail_path": if thumbnail_path.get().is_empty() { None::<String> } else { Some(thumbnail_path.get()) }
            });

            spawn_local(async move {
                let response = Request::put(&format!("{}/realms/{}/avatars/{}", api_base, realm_slug, avatar_id))
                    .json(&data)
                    .unwrap()
                    .send()
                    .await;

                set_pending.set(false);

                match response {
                    Ok(resp) if resp.ok() => {
                        set_message.set(Some(("Avatar updated successfully!".to_string(), true)));
                    }
                    Ok(_) => {
                        set_message.set(Some(("Failed to update avatar".to_string(), false)));
                    }
                    Err(_) => {
                        set_message.set(Some(("Network error".to_string(), false)));
                    }
                }
            });
        }
    };

    #[cfg(feature = "hydrate")]
    let avatar_id_for_delete = avatar.id.clone();
    #[cfg(feature = "hydrate")]
    let realm_slug_for_delete_api = realm_slug_for_delete.clone();

    let on_delete = move || {
        set_delete_pending.set(true);

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

            let api_base = get_api_base();
            let avatar_id = avatar_id_for_delete.clone();
            let realm_slug = realm_slug_for_delete_api.clone();
            let nav_slug = realm_slug_for_delete.clone();

            spawn_local(async move {
                let response = Request::delete(&format!("{}/realms/{}/avatars/{}", api_base, realm_slug, avatar_id))
                    .send()
                    .await;

                set_delete_pending.set(false);

                match response {
                    Ok(resp) if resp.ok() => {
                        // Navigate back to avatars list
                        crate::utils::navigate_to(&format!("/admin/realms/{}/avatars", nav_slug));
                    }
                    Ok(_) => {
                        set_message.set(Some(("Failed to delete avatar".to_string(), false)));
                    }
                    Err(_) => {
                        set_message.set(Some(("Network error".to_string(), false)));
                    }
                }
            });
        }
    };

    // Clone for the view
    let avatar_name_header = avatar.name.clone();
    let avatar_desc_header = avatar.description.clone().unwrap_or_default();
    let avatar_id_display = avatar.id.clone();
    let avatar_created = avatar.created_at.clone();
    let avatar_updated = avatar.updated_at.clone();

    // Additional clone for the closure
    let avatar_name_for_alt = avatar_name_header.clone();

    view! {
        <Card>
            <div class="avatar-header" style="display: flex; align-items: center; gap: 16px; margin-bottom: 16px;">
                {move || {
                    let name_for_alt = avatar_name_for_alt.clone();
                    thumbnail_preview().map(move |url| view! {
                        <img
                            src=url
                            alt=name_for_alt
                            style="width: 80px; height: 80px; object-fit: contain; border-radius: 8px; background: var(--bg-secondary, #1e293b);"
                        />
                    })
                }}
                <div class="avatar-info">
                    <h2>{avatar_name_header}</h2>
                    <p class="text-muted">{avatar_desc_header}</p>
                </div>
                <div class="avatar-badges" style="margin-left: auto; display: flex; gap: 8px;">
                    {if avatar.is_public {
                        view! { <span class="status-badge status-active">"Public"</span> }.into_any()
                    } else {
                        view! { <span class="status-badge status-inactive">"Private"</span> }.into_any()
                    }}
                    {if avatar.is_active {
                        view! { <span class="status-badge status-active">"Active"</span> }.into_any()
                    } else {
                        view! { <span class="status-badge status-inactive">"Inactive"</span> }.into_any()
                    }}
                </div>
            </div>

            <DetailGrid>
                <DetailItem label="ID">
                    <code>{avatar_id_display}</code>
                </DetailItem>
                <DetailItem label="Slug">
                    <code>{slug_display}</code>
                </DetailItem>
                <DetailItem label="Realm">
                    <a href=format!("/admin/realms/{}", realm_slug) class="table-link">
                        {realm_slug.clone()}
                    </a>
                </DetailItem>
                <DetailItem label="Created">
                    {avatar_created}
                </DetailItem>
                <DetailItem label="Updated">
                    {avatar_updated}
                </DetailItem>
            </DetailGrid>
        </Card>

        <Card title="Edit Avatar Settings">
            <form on:submit=on_submit>
                <div class="form-group">
                    <label for="name" class="form-label">"Name"</label>
                    <input
                        type="text"
                        id="name"
                        required=true
                        class="form-input"
                        prop:value=move || name.get()
                        on:input=move |ev| set_name.set(event_target_value(&ev))
                    />
                </div>

                <div class="form-group">
                    <label for="description" class="form-label">"Description"</label>
                    <textarea
                        id="description"
                        class="form-textarea"
                        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/avatar-name.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>

                <div class="form-row">
                    <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."</small>
                    </div>
                    <div class="checkbox-group">
                        <label class="checkbox-label">
                            <input
                                type="checkbox"
                                class="form-checkbox"
                                prop:checked=move || is_active.get()
                                on:change=move |ev| set_is_active.set(event_target_checked(&ev))
                            />
                            "Active"
                        </label>
                        <small class="form-help">"Inactive avatars are not shown to users."</small>
                    </div>
                </div>

                <MessageAlert message=message />

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

        <Card title="Danger Zone" class="danger-zone">
            <p class="text-warning">"Deleting an avatar is permanent and cannot be undone."</p>
            <DeleteConfirmation
                message="Are you sure you want to delete this avatar? This action cannot be undone."
                button_text="Delete Avatar"
                confirm_text="Yes, Delete Avatar"
                pending=delete_pending
                on_confirm=on_delete
            />
        </Card>
    }
}
