use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use wasm_bindgen::JsCast;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuickLink {
    pub id: String,
    pub title: String,
    pub description: String,
    pub icon: String,
    pub url: String,
    pub category: LinkCategory,
    pub external: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum LinkCategory {
    GettingStarted,
    UserGuides,
    Architecture,
    API,
    Troubleshooting,
}

impl LinkCategory {
    fn title(&self) -> &'static str {
        match self {
            Self::GettingStarted => "Getting Started",
            Self::UserGuides => "User Guides",
            Self::Architecture => "Architecture",
            Self::API => "API Reference",
            Self::Troubleshooting => "Troubleshooting",
        }
    }

    fn icon(&self) -> &'static str {
        match self {
            Self::GettingStarted => "🚀",
            Self::UserGuides => "📖",
            Self::Architecture => "🏗️",
            Self::API => "🔌",
            Self::Troubleshooting => "🔧",
        }
    }
}

#[component]
pub fn QuickLinks(#[prop(into, optional)] collapsed: Signal<bool>) -> impl IntoView {
    let (selected_category, set_selected_category) = signal(LinkCategory::GettingStarted);
    let (search_query, set_search_query) = signal(String::new());

    let all_links = move || {
        vec![
            // Getting Started
            QuickLink {
                id: "quickstart".to_string(),
                title: "Quick Start Guide".to_string(),
                description: "Get up and running in minutes".to_string(),
                icon: "⚡".to_string(),
                url: "/docs/quickstart".to_string(),
                category: LinkCategory::GettingStarted,
                external: false,
            },
            QuickLink {
                id: "from-scratch".to_string(),
                title: "Deploy From Scratch".to_string(),
                description: "Complete deployment walkthrough".to_string(),
                icon: "🎯".to_string(),
                url: "/docs/guides/from-scratch".to_string(),
                category: LinkCategory::GettingStarted,
                external: false,
            },
            QuickLink {
                id: "installation".to_string(),
                title: "Installation Guide".to_string(),
                description: "System prerequisites and setup".to_string(),
                icon: "📦".to_string(),
                url: "/docs/installation".to_string(),
                category: LinkCategory::GettingStarted,
                external: false,
            },
            // User Guides
            QuickLink {
                id: "server-management".to_string(),
                title: "Server Management".to_string(),
                description: "Create, configure, and manage servers".to_string(),
                icon: "🖥️".to_string(),
                url: "/docs/user/server-guide".to_string(),
                category: LinkCategory::UserGuides,
                external: false,
            },
            QuickLink {
                id: "taskserv-guide".to_string(),
                title: "Task Services Guide".to_string(),
                description: "Install and configure infrastructure services".to_string(),
                icon: "⚙️".to_string(),
                url: "/docs/user/taskserv-guide".to_string(),
                category: LinkCategory::UserGuides,
                external: false,
            },
            QuickLink {
                id: "workspace-guide".to_string(),
                title: "Workspace Management".to_string(),
                description: "Organize and switch between workspaces".to_string(),
                icon: "📁".to_string(),
                url: "/docs/user/workspace-guide".to_string(),
                category: LinkCategory::UserGuides,
                external: false,
            },
            QuickLink {
                id: "test-environments".to_string(),
                title: "Test Environments".to_string(),
                description: "Containerized testing workflows".to_string(),
                icon: "🧪".to_string(),
                url: "/docs/user/test-environment-guide".to_string(),
                category: LinkCategory::UserGuides,
                external: false,
            },
            // Architecture
            QuickLink {
                id: "architecture-overview".to_string(),
                title: "Architecture Overview".to_string(),
                description: "System design and components".to_string(),
                icon: "🏛️".to_string(),
                url: "/docs/architecture/overview".to_string(),
                category: LinkCategory::Architecture,
                external: false,
            },
            QuickLink {
                id: "orchestrator".to_string(),
                title: "Orchestrator Architecture".to_string(),
                description: "Hybrid Rust/Nushell coordination layer".to_string(),
                icon: "🎯".to_string(),
                url: "/docs/architecture/orchestrator".to_string(),
                category: LinkCategory::Architecture,
                external: false,
            },
            QuickLink {
                id: "batch-workflows".to_string(),
                title: "Batch Workflow System".to_string(),
                description: "Provider-agnostic batch operations".to_string(),
                icon: "📦".to_string(),
                url: "/docs/architecture/batch-workflows".to_string(),
                category: LinkCategory::Architecture,
                external: false,
            },
            // API Reference
            QuickLink {
                id: "rest-api".to_string(),
                title: "REST API Reference".to_string(),
                description: "Complete HTTP API documentation".to_string(),
                icon: "🌐".to_string(),
                url: "/docs/api/rest-api".to_string(),
                category: LinkCategory::API,
                external: false,
            },
            QuickLink {
                id: "websocket".to_string(),
                title: "WebSocket API".to_string(),
                description: "Real-time event streaming".to_string(),
                icon: "⚡".to_string(),
                url: "/docs/api/websocket".to_string(),
                category: LinkCategory::API,
                external: false,
            },
            QuickLink {
                id: "nushell-plugins".to_string(),
                title: "Nushell Plugins".to_string(),
                description: "Native plugin integration guide".to_string(),
                icon: "🔌".to_string(),
                url: "/docs/user/nushell-plugins-guide".to_string(),
                category: LinkCategory::API,
                external: false,
            },
            // Troubleshooting
            QuickLink {
                id: "troubleshooting".to_string(),
                title: "Troubleshooting Guide".to_string(),
                description: "Common issues and solutions".to_string(),
                icon: "🔍".to_string(),
                url: "/docs/user/troubleshooting-guide".to_string(),
                category: LinkCategory::Troubleshooting,
                external: false,
            },
            QuickLink {
                id: "faq".to_string(),
                title: "FAQ".to_string(),
                description: "Frequently asked questions".to_string(),
                icon: "❓".to_string(),
                url: "/docs/faq".to_string(),
                category: LinkCategory::Troubleshooting,
                external: false,
            },
        ]
    };

    let filtered_links = move || {
        let query = search_query.get().to_lowercase();
        let category = selected_category.get();

        all_links()
            .into_iter()
            .filter(|link| {
                // Filter by category
                link.category == category &&
                // Filter by search query
                (query.is_empty() ||
                 link.title.to_lowercase().contains(&query) ||
                 link.description.to_lowercase().contains(&query))
            })
            .collect::<Vec<_>>()
    };

    let categories = StoredValue::new(vec![
        LinkCategory::GettingStarted,
        LinkCategory::UserGuides,
        LinkCategory::Architecture,
        LinkCategory::API,
        LinkCategory::Troubleshooting,
    ]);

    view! {
        <div class="quick-links" style=move || format!(
            "background: white; height: 100vh; overflow-y: auto; box-shadow: 2px 0 8px rgba(0,0,0,0.1); transition: width 0.3s; {}",
            if collapsed.get() { "width: 60px;" } else { "width: 320px;" }
        )>
            // Header
            <div style="padding: 20px; border-bottom: 1px solid #e5e7eb;">
                <Show when=move || !collapsed.get()>
                    <h3 style="margin: 0 0 15px 0; font-size: 1.3rem; color: #1f2937; font-weight: 600;">
                        "📚 Quick Links"
                    </h3>

                    // Search box
                    <input
                        type="text"
                        placeholder="Search documentation..."
                        prop:value=move || search_query.get()
                        on:input=move |ev| set_search_query.set(event_target_value(&ev))
                        style="width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.9rem;"
                    />
                </Show>

                <Show when=move || collapsed.get()>
                    <div style="text-align: center; font-size: 1.5rem;">
                        "📚"
                    </div>
                </Show>
            </div>

            // Category tabs
            <Show when=move || !collapsed.get()>
                <div style="padding: 15px; border-bottom: 1px solid #e5e7eb;">
                    <div style="display: flex; flex-direction: column; gap: 5px;">
                        {categories.get_value().into_iter().map(|category| {
                            let cat = category;
                            view! {
                                <button
                                    on:click=move |_| set_selected_category.set(cat)
                                    style=move || format!(
                                        "padding: 10px 12px; border: none; border-radius: 6px; cursor: pointer; text-align: left; font-size: 0.9rem; font-weight: 500; transition: all 0.2s; {}",
                                        if selected_category.get() == cat {
                                            "background: #3b82f6; color: white;"
                                        } else {
                                            "background: transparent; color: #374151;"
                                        }
                                    )
                                >
                                    <span style="margin-right: 8px;">{category.icon()}</span>
                                    {category.title()}
                                </button>
                            }
                        }).collect_view()}
                    </div>
                </div>
            </Show>

            // Links list
            <Show when=move || !collapsed.get()>
                <div style="padding: 15px;">
                    <Show
                        when=move || !filtered_links().is_empty()
                        fallback=move || view! {
                            <div style="padding: 20px; text-align: center; color: #6b7280;">
                                <div style="font-size: 2rem; margin-bottom: 10px;">"🔍"</div>
                                <p style="margin: 0; font-size: 0.9rem;">"No results found"</p>
                            </div>
                        }
                    >
                        <div style="display: flex; flex-direction: column; gap: 10px;">
                            {move || filtered_links().into_iter().map(|link| {
                                view! {
                                    <a
                                        href={link.url.clone()}
                                        target={if link.external { "_blank" } else { "_self" }}
                                        style="padding: 12px; background: #f9fafb; border-radius: 8px; text-decoration: none; transition: all 0.2s; border: 1px solid transparent; display: block;"
                                        on:mouseenter=move |ev| {
                                            if let Some(target) = ev.target() {
                                                if let Ok(element) = target.dyn_into::<web_sys::HtmlElement>() {
                                                    let _ = element.style().set_property("background", "#eff6ff");
                                                    let _ = element.style().set_property("border-color", "#3b82f6");
                                                }
                                            }
                                        }
                                        on:mouseleave=move |ev| {
                                            if let Some(target) = ev.target() {
                                                if let Ok(element) = target.dyn_into::<web_sys::HtmlElement>() {
                                                    let _ = element.style().set_property("background", "#f9fafb");
                                                    let _ = element.style().set_property("border-color", "transparent");
                                                }
                                            }
                                        }
                                    >
                                        <div style="display: flex; align-items: start; gap: 10px;">
                                            <div style="font-size: 1.3rem; flex-shrink: 0;">
                                                {link.icon}
                                            </div>
                                            <div style="flex: 1; min-width: 0;">
                                                <div style="font-weight: 600; color: #1f2937; font-size: 0.9rem; margin-bottom: 4px;">
                                                    {link.title}
                                                </div>
                                                <div style="color: #6b7280; font-size: 0.8rem; line-height: 1.4;">
                                                    {link.description}
                                                </div>
                                            </div>
                                            {if link.external {
                                                view! {
                                                    <div style="color: #9ca3af; font-size: 0.8rem; flex-shrink: 0;">
                                                        "↗"
                                                    </div>
                                                }.into_any()
                                            } else {
                                                ().into_any()
                                            }}
                                        </div>
                                    </a>
                                }
                            }).collect_view()}
                        </div>
                    </Show>
                </div>
            </Show>

            // Collapsed mode - show category icons only
            <Show when=move || collapsed.get()>
                <div style="padding: 10px; display: flex; flex-direction: column; align-items: center; gap: 15px;">
                    {categories.get_value().into_iter().map(|category| {
                        let cat = category;
                        view! {
                            <button
                                on:click=move |_| set_selected_category.set(cat)
                                style=move || format!(
                                    "width: 40px; height: 40px; border: none; border-radius: 8px; cursor: pointer; font-size: 1.3rem; transition: all 0.2s; {}",
                                    if selected_category.get() == cat {
                                        "background: #3b82f6;"
                                    } else {
                                        "background: #f3f4f6;"
                                    }
                                )
                                title={category.title()}
                            >
                                {category.icon()}
                            </button>
                        }
                    }).collect_view()}
                </div>
            </Show>

            // Footer
            <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 15px; border-top: 1px solid #e5e7eb; background: white;">
                <Show when=move || !collapsed.get()>
                    <div style="background: #f0f9ff; padding: 12px; border-radius: 6px; border-left: 3px solid #3b82f6;">
                        <p style="margin: 0; color: #1e40af; font-size: 0.8rem; line-height: 1.5;">
                            <strong>"💡 Tip:"</strong>" Press "
                            <code style="background: white; padding: 2px 6px; border-radius: 3px;">"Ctrl+K"</code>
                            " to quickly search docs"
                        </p>
                    </div>
                </Show>
            </div>
        </div>
    }
}
