use crate::components::{skill_data, SkillCategorySection};
use crate::Route;
use dioxus::prelude::*;

#[component]
pub fn Skills() -> Element {
    let skill_categories = skill_data::get_all_skill_categories();
    let mut search_query = use_signal(|| String::new());

    let filtered_categories = use_memo(move || {
        let query = search_query.read().to_lowercase();
        if query.is_empty() {
            skill_categories.clone()
        } else {
            skill_categories
                .iter()
                .map(|category| {
                    let filtered_skills: Vec<_> = category
                        .skills
                        .iter()
                        .filter(|skill| skill.name.to_lowercase().contains(&query))
                        .cloned()
                        .collect();

                    crate::components::SkillCategory {
                        name: category.name,
                        skills: filtered_skills,
                    }
                })
                .filter(|category| !category.skills.is_empty()) // Only show categories with matching skills
                .collect()
        }
    });

    rsx! {
        div { class: "content",
            div { class: "flex-1 col gap-5 px-2 sm:px-4 md:px-6 py-4 sm:py-8 md:py-12",
                h1 {
                    class: "font-[var(--title-f)] font-black tracking-[4px] text-center text-2.5em sm:text-[3em] md:text-[3.5em] lg:text-[4em]",
                    "Skills"
                }

                div { class: "flex-1",
                    div { class: "w-full row",
                        input {
                            class: "text-[inherit] bg-transparent border-[1px] border-solid border-[var(--border)] px-[20px] py-[10px] rounded-[15px] flex-1 text-[1.15em] w-full",
                            type: "text",
                            placeholder: "Search skills...",
                            value: "{search_query}",
                            oninput: move |event| {
                                search_query.set(event.value());
                            }
                        }
                    }

                    div { class: "w-full col flex-1",
                        div { class: "col mt-5 gap-7",
                            if filtered_categories().is_empty() && !search_query.read().is_empty() {
                                div {
                                    class: "text-center py-8 text-[var(--secondary-text)]",
                                    "No skills found matching your search."
                                }
                            } else {
                                for category in filtered_categories() {
                                    SkillCategorySection { category: category }
                                }
                            }
                        }
                    }
                }
            }
        }
        Outlet::<Route> {}
    }
}
