//! Inventory popup component.

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

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

use super::modals::{GuestLockedOverlay, Modal};
use super::tabs::{Tab, TabBar};
use super::ws_client::WsSender;

/// Inventory popup component.
///
/// Shows a tabbed interface with:
/// - My Inventory: User-owned props with drop functionality
/// - Server: Public server-wide props
/// - Realm: Public realm-specific props
///
/// Props:
/// - `open`: Signal controlling visibility
/// - `on_close`: Callback when popup should close
/// - `ws_sender`: WebSocket sender for dropping props
/// - `realm_slug`: Current realm slug for fetching realm props
/// - `is_guest`: Whether the current user is a guest (shows locked overlay)
#[component]
pub fn InventoryPopup(
    #[prop(into)] open: Signal<bool>,
    on_close: Callback<()>,
    ws_sender: StoredValue<Option<WsSender>, LocalStorage>,
    #[prop(into)] realm_slug: Signal<String>,
    /// Whether the current user is a guest. Guests see a locked overlay.
    #[prop(optional, into)]
    is_guest: Option<Signal<bool>>,
) -> impl IntoView {
    let is_guest = is_guest.unwrap_or_else(|| Signal::derive(|| false));
    // Tab state
    let (active_tab, set_active_tab) = signal("my_inventory");

    // My Inventory state
    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);

    // Server props state
    let (server_props, set_server_props) = signal(Vec::<PublicProp>::new());
    let (server_loading, set_server_loading) = signal(false);
    let (server_error, set_server_error) = signal(Option::<String>::None);

    // Realm props state
    let (realm_props, set_realm_props) = signal(Vec::<PublicProp>::new());
    let (realm_loading, set_realm_loading) = signal(false);
    let (realm_error, set_realm_error) = signal(Option::<String>::None);

    // Track if tabs have been loaded (to avoid re-fetching)
    let (my_inventory_loaded, set_my_inventory_loaded) = signal(false);
    let (server_loaded, set_server_loaded) = signal(false);
    let (realm_loaded, set_realm_loaded) = signal(false);

    // Fetch my inventory when popup opens or tab is selected
    #[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);
                set_my_inventory_loaded.set(false);
                set_server_loaded.set(false);
                set_realm_loaded.set(false);
                return;
            }

            // Only fetch if on my_inventory tab and not already loaded
            if active_tab.get() != "my_inventory" || my_inventory_loaded.get() {
                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);
                            set_my_inventory_loaded.set(true);
                        } 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);
            });
        });
    }

    // Fetch server props when server tab is selected
    #[cfg(feature = "hydrate")]
    {
        use gloo_net::http::Request;
        use leptos::task::spawn_local;

        Effect::new(move |_| {
            if !open.get() || active_tab.get() != "server" || server_loaded.get() {
                return;
            }

            set_server_loading.set(true);
            set_server_error.set(None);

            spawn_local(async move {
                let response = Request::get("/api/inventory/server").send().await;
                match response {
                    Ok(resp) if resp.ok() => {
                        if let Ok(data) = resp
                            .json::<chattyness_db::models::PublicPropsResponse>()
                            .await
                        {
                            set_server_props.set(data.props);
                            set_server_loaded.set(true);
                        } else {
                            set_server_error.set(Some("Failed to parse server props".to_string()));
                        }
                    }
                    Ok(resp) => {
                        set_server_error.set(Some(format!(
                            "Failed to load server props: {}",
                            resp.status()
                        )));
                    }
                    Err(e) => {
                        set_server_error.set(Some(format!("Network error: {}", e)));
                    }
                }
                set_server_loading.set(false);
            });
        });
    }

    // Fetch realm props when realm tab is selected
    #[cfg(feature = "hydrate")]
    {
        use gloo_net::http::Request;
        use leptos::task::spawn_local;

        Effect::new(move |_| {
            if !open.get() || active_tab.get() != "realm" || realm_loaded.get() {
                return;
            }

            let slug = realm_slug.get();
            if slug.is_empty() {
                set_realm_error.set(Some("No realm selected".to_string()));
                return;
            }

            set_realm_loading.set(true);
            set_realm_error.set(None);

            spawn_local(async move {
                let response = Request::get(&format!("/api/realms/{}/inventory", slug))
                    .send()
                    .await;
                match response {
                    Ok(resp) if resp.ok() => {
                        if let Ok(data) = resp
                            .json::<chattyness_db::models::PublicPropsResponse>()
                            .await
                        {
                            set_realm_props.set(data.props);
                            set_realm_loaded.set(true);
                        } else {
                            set_realm_error.set(Some("Failed to parse realm props".to_string()));
                        }
                    }
                    Ok(resp) => {
                        set_realm_error.set(Some(format!(
                            "Failed to load realm props: {}",
                            resp.status()
                        )));
                    }
                    Err(e) => {
                        set_realm_error.set(Some(format!("Network error: {}", e)));
                    }
                }
                set_realm_loading.set(false);
            });
        });
    }

    // 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| {};

    view! {
        <Modal
            open=open
            on_close=on_close
            title="Inventory"
            title_id="inventory-modal-title"
            max_width="max-w-2xl"
            class="max-h-[80vh] flex flex-col"
        >
            <div class="relative flex-1 flex flex-col">
                // Tab bar
                <TabBar
                    tabs=vec![
                        Tab::new("my_inventory", "My Inventory"),
                        Tab::new("server", "Server"),
                        Tab::new("realm", "Realm"),
                    ]
                    active=Signal::derive(move || active_tab.get())
                    on_select=Callback::new(move |id| set_active_tab.set(id))
                />

                // Tab content
                <div class="flex-1 overflow-y-auto min-h-[300px]">
                    // My Inventory tab
                    <Show when=move || active_tab.get() == "my_inventory">
                        <MyInventoryTab
                            items=items
                            loading=loading
                            error=error
                            selected_item=selected_item
                            set_selected_item=set_selected_item
                            dropping=dropping
                            on_drop=Callback::new(handle_drop)
                        />
                    </Show>

                    // Server tab
                    <Show when=move || active_tab.get() == "server">
                        <PublicPropsTab
                            props=server_props
                            loading=server_loading
                            error=server_error
                            tab_name="Server"
                            empty_message="No public server props available"
                        />
                    </Show>

                    // Realm tab
                    <Show when=move || active_tab.get() == "realm">
                        <PublicPropsTab
                            props=realm_props
                            loading=realm_loading
                            error=realm_error
                            tab_name="Realm"
                            empty_message="No public realm props available"
                        />
                    </Show>
                </div>

                // Guest locked overlay
                <Show when=move || is_guest.get()>
                    <GuestLockedOverlay />
                </Show>
            </div>
        </Modal>
    }
}

/// My Inventory tab content with drop functionality.
#[component]
fn MyInventoryTab(
    #[prop(into)] items: Signal<Vec<InventoryItem>>,
    #[prop(into)] loading: Signal<bool>,
    #[prop(into)] error: Signal<Option<String>>,
    #[prop(into)] selected_item: Signal<Option<Uuid>>,
    set_selected_item: WriteSignal<Option<Uuid>>,
    #[prop(into)] dropping: Signal<bool>,
    #[prop(into)] on_drop: Callback<Uuid>,
) -> impl IntoView {
    view! {
        // 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>
                <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>

                // 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 on_drop = on_drop.clone();
                    let is_dropping = dropping.get();
                    let is_droppable = item.is_droppable;

                    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 { "" }}
                                        {if is_droppable { " \u{2022} Droppable" } else { " \u{2022} Essential" }}
                                    </p>
                                </div>
                                <div class="flex gap-2">
                                    // Drop button - disabled for non-droppable (essential) props
                                    <button
                                        type="button"
                                        class=if is_droppable {
                                            "px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50"
                                        } else {
                                            "px-4 py-2 bg-gray-600 text-gray-400 rounded-lg cursor-not-allowed"
                                        }
                                        on:click=move |_| {
                                            if is_droppable {
                                                on_drop.run(item_id);
                                            }
                                        }
                                        disabled=is_dropping || !is_droppable
                                        title=if is_droppable { "" } else { "Essential prop cannot be dropped" }
                                    >
                                        {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>
        </Show>
    }
}

/// Public props tab content (read-only display).
#[component]
fn PublicPropsTab(
    #[prop(into)] props: Signal<Vec<PublicProp>>,
    #[prop(into)] loading: Signal<bool>,
    #[prop(into)] error: Signal<Option<String>>,
    tab_name: &'static str,
    empty_message: &'static str,
) -> impl IntoView {
    // Selected prop for showing details
    let (selected_prop, set_selected_prop) = signal(Option::<Uuid>::None);

    view! {
        // Loading state
        <Show when=move || loading.get()>
            <div class="flex items-center justify-center py-12">
                <p class="text-gray-400">{format!("Loading {} props...", tab_name.to_lowercase())}</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() && props.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">{empty_message}</p>
                <p class="text-gray-500 text-sm mt-1">"Public props will appear here when available"</p>
            </div>
        </Show>

        // Grid of props
        <Show when=move || !loading.get() && !props.get().is_empty()>
            <div>
                <div
                    class="grid grid-cols-4 sm:grid-cols-6 gap-2"
                    role="listbox"
                    aria-label=format!("{} props", tab_name)
                >
                    <For
                        each=move || props.get()
                        key=|prop| prop.id
                        children=move |prop: PublicProp| {
                            let prop_id = prop.id;
                            let prop_name = prop.name.clone();
                            let is_selected = move || selected_prop.get() == Some(prop_id);
                            let asset_path = if prop.asset_path.starts_with('/') {
                                prop.asset_path.clone()
                            } else {
                                format!("/static/{}", 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_prop.set(Some(prop_id));
                                    }
                                    role="option"
                                    aria-selected=is_selected
                                    aria-label=prop_name
                                >
                                    <img
                                        src=asset_path
                                        alt=""
                                        class="w-full h-full object-contain"
                                    />
                                </button>
                            }
                        }
                    />
                </div>

                // Selected prop details (read-only)
                {move || {
                    let prop_id = selected_prop.get()?;
                    let prop = props.get().into_iter().find(|p| p.id == prop_id)?;

                    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">{prop.name.clone()}</h3>
                                    {prop.description.map(|desc| view! {
                                        <p class="text-gray-400 text-sm">{desc}</p>
                                    })}
                                </div>
                                <p class="text-gray-500 text-sm italic">"View only"</p>
                            </div>
                        </div>
                    })
                }}
            </div>
        </Show>
    }
}
