//! Inventory popup component.

use leptos::prelude::*;
use leptos::reactive::owner::LocalStorage;
use uuid::Uuid;

use chattyness_db::models::InventoryItem;
#[cfg(feature = "hydrate")]
use chattyness_db::ws_messages::ClientMessage;

use super::ws_client::WsSender;

/// Inventory popup component.
///
/// Shows a grid of user-owned props with drop functionality.
///
/// Props:
/// - `open`: Signal controlling visibility
/// - `on_close`: Callback when popup should close
/// - `ws_sender`: WebSocket sender for dropping props
#[component]
pub fn InventoryPopup(
    #[prop(into)] open: Signal<bool>,
    on_close: Callback<()>,
    ws_sender: StoredValue<Option<WsSender>, LocalStorage>,
) -> impl IntoView {
    let (items, set_items) = signal(Vec::<InventoryItem>::new());
    let (loading, set_loading) = signal(false);
    let (error, set_error) = signal(Option::<String>::None);
    let (selected_item, set_selected_item) = signal(Option::<Uuid>::None);
    let (dropping, set_dropping) = signal(false);

    // Fetch inventory when popup opens
    #[cfg(feature = "hydrate")]
    {
        use gloo_net::http::Request;
        use leptos::task::spawn_local;

        Effect::new(move |_| {
            if !open.get() {
                // Reset state when closing
                set_selected_item.set(None);
                return;
            }

            set_loading.set(true);
            set_error.set(None);

            spawn_local(async move {
                let response = Request::get("/api/inventory").send().await;
                match response {
                    Ok(resp) if resp.ok() => {
                        if let Ok(data) =
                            resp.json::<chattyness_db::models::InventoryResponse>().await
                        {
                            set_items.set(data.items);
                        } else {
                            set_error.set(Some("Failed to parse inventory data".to_string()));
                        }
                    }
                    Ok(resp) => {
                        set_error.set(Some(format!("Failed to load inventory: {}", resp.status())));
                    }
                    Err(e) => {
                        set_error.set(Some(format!("Network error: {}", e)));
                    }
                }
                set_loading.set(false);
            });
        });
    }

    // Handle escape key to close
    #[cfg(feature = "hydrate")]
    {
        use wasm_bindgen::{closure::Closure, JsCast};

        Effect::new(move |_| {
            if !open.get() {
                return;
            }

            let on_close_clone = on_close.clone();
            let closure =
                Closure::<dyn Fn(web_sys::KeyboardEvent)>::new(move |ev: web_sys::KeyboardEvent| {
                    if ev.key() == "Escape" {
                        on_close_clone.run(());
                    }
                });

            if let Some(window) = web_sys::window() {
                let _ = window.add_event_listener_with_callback(
                    "keydown",
                    closure.as_ref().unchecked_ref(),
                );
            }

            // Intentionally not cleaning up - closure lives for session
            closure.forget();
        });
    }

    // Handle drop action via WebSocket
    #[cfg(feature = "hydrate")]
    let handle_drop = {
        move |item_id: Uuid| {
            set_dropping.set(true);

            // Send drop command via WebSocket
            ws_sender.with_value(|sender| {
                if let Some(send_fn) = sender {
                    send_fn(ClientMessage::DropProp {
                        inventory_item_id: item_id,
                    });
                    // Optimistically remove from local list
                    set_items.update(|items| {
                        items.retain(|i| i.id != item_id);
                    });
                    set_selected_item.set(None);
                } else {
                    set_error.set(Some("Not connected to server".to_string()));
                }
            });

            set_dropping.set(false);
        }
    };

    #[cfg(not(feature = "hydrate"))]
    let handle_drop = |_item_id: Uuid| {};

    let on_close_backdrop = on_close.clone();
    let on_close_button = on_close.clone();

    view! {
        <Show when=move || open.get()>
            <div
                class="fixed inset-0 z-50 flex items-center justify-center"
                role="dialog"
                aria-modal="true"
                aria-labelledby="inventory-modal-title"
            >
                // Backdrop
                <div
                    class="absolute inset-0 bg-black/70 backdrop-blur-sm"
                    on:click=move |_| on_close_backdrop.run(())
                    aria-hidden="true"
                />

                // Modal content
                <div class="relative bg-gray-800 rounded-lg shadow-2xl max-w-2xl w-full mx-4 p-6 border border-gray-700 max-h-[80vh] flex flex-col">
                    // Header
                    <div class="flex items-center justify-between mb-4">
                        <h2 id="inventory-modal-title" class="text-xl font-bold text-white">
                            "Inventory"
                        </h2>
                        <button
                            type="button"
                            class="text-gray-400 hover:text-white transition-colors"
                            on:click=move |_| on_close_button.run(())
                            aria-label="Close inventory"
                        >
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </button>
                    </div>

                    // Loading state
                    <Show when=move || loading.get()>
                        <div class="flex items-center justify-center py-12">
                            <p class="text-gray-400">"Loading inventory..."</p>
                        </div>
                    </Show>

                    // Error state
                    <Show when=move || error.get().is_some()>
                        <div class="bg-red-900/20 border border-red-600 rounded p-4 mb-4">
                            <p class="text-red-400">{move || error.get().unwrap_or_default()}</p>
                        </div>
                    </Show>

                    // Empty state
                    <Show when=move || !loading.get() && error.get().is_none() && items.get().is_empty()>
                        <div class="flex flex-col items-center justify-center py-12 text-center">
                            <div class="w-16 h-16 rounded-full bg-gray-700/50 flex items-center justify-center mb-4">
                                <svg class="w-8 h-8 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
                                </svg>
                            </div>
                            <p class="text-gray-400">"Your inventory is empty"</p>
                            <p class="text-gray-500 text-sm mt-1">"Collect props to see them here"</p>
                        </div>
                    </Show>

                    // Grid of items
                    <Show when=move || !loading.get() && !items.get().is_empty()>
                        <div class="flex-1 overflow-y-auto">
                            <div
                                class="grid grid-cols-4 sm:grid-cols-6 gap-2"
                                role="listbox"
                                aria-label="Inventory items"
                            >
                                <For
                                    each=move || items.get()
                                    key=|item| item.id
                                    children=move |item: InventoryItem| {
                                        let item_id = item.id;
                                        let item_name = item.prop_name.clone();
                                        let is_selected = move || selected_item.get() == Some(item_id);
                                        let asset_path = if item.prop_asset_path.starts_with('/') {
                                            item.prop_asset_path.clone()
                                        } else {
                                            format!("/static/{}", item.prop_asset_path)
                                        };

                                        view! {
                                            <button
                                                type="button"
                                                class=move || format!(
                                                    "aspect-square rounded-lg border-2 transition-all p-1 focus:outline-none focus:ring-2 focus:ring-blue-500 {}",
                                                    if is_selected() {
                                                        "border-blue-500 bg-blue-900/30"
                                                    } else {
                                                        "border-gray-600 hover:border-gray-500 bg-gray-700/50"
                                                    }
                                                )
                                                on:click=move |_| {
                                                    set_selected_item.set(Some(item_id));
                                                }
                                                role="option"
                                                aria-selected=is_selected
                                                aria-label=item_name
                                            >
                                                <img
                                                    src=asset_path
                                                    alt=""
                                                    class="w-full h-full object-contain"
                                                />
                                            </button>
                                        }
                                    }
                                />
                            </div>
                        </div>
                    </Show>

                    // Selected item details and actions
                    {move || {
                        let item_id = selected_item.get()?;
                        let item = items.get().into_iter().find(|i| i.id == item_id)?;
                        let handle_drop = handle_drop.clone();
                        let is_dropping = dropping.get();

                        Some(view! {
                            <div class="mt-4 pt-4 border-t border-gray-700">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <h3 class="text-white font-medium">{item.prop_name.clone()}</h3>
                                        <p class="text-gray-400 text-sm">
                                            {if item.is_transferable { "Transferable" } else { "Not transferable" }}
                                            {if item.is_portable { " \u{2022} Portable" } else { "" }}
                                        </p>
                                    </div>
                                    <div class="flex gap-2">
                                        // Drop button
                                        <button
                                            type="button"
                                            class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50"
                                            on:click=move |_| handle_drop(item_id)
                                            disabled=is_dropping
                                        >
                                            {if is_dropping { "Dropping..." } else { "Drop" }}
                                        </button>
                                        // Transfer button (disabled for now)
                                        <Show when=move || item.is_transferable>
                                            <button
                                                type="button"
                                                class="px-4 py-2 bg-gray-600 text-gray-400 rounded-lg cursor-not-allowed"
                                                disabled=true
                                                title="Transfer functionality coming soon"
                                            >
                                                "Transfer"
                                            </button>
                                        </Show>
                                    </div>
                                </div>
                            </div>
                        })
                    }}
                </div>
            </div>
        </Show>
    }
}
