use dioxus::prelude::*;

use crate::app::Route;
use crate::components::page_header::PageHeader;
use crate::infrastructure::onboarding::fetch_targets;

#[component]
pub fn GraphIndexPage() -> Element {
    let repos = use_resource(|| async { fetch_targets().await.ok() });

    rsx! {
        PageHeader {
            title: "Code Knowledge Graph",
            description: "Select a repository to explore its code graph",
        }

        match &*repos.read() {
            Some(Some(data)) => {
                let repo_list = &data.data;
                if repo_list.is_empty() {
                    rsx! {
                        div { class: "card",
                            p { "No repositories found. Add a repository first." }
                        }
                    }
                } else {
                    rsx! {
                        div { class: "graph-index-grid",
                            for repo in repo_list {
                                {
                                    let repo_id = repo.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str()).unwrap_or_default().to_string();
                                    let name = repo.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string();
                                    let url = repo
                                        .get("artifacts")
                                        .and_then(|a| a.as_array())
                                        .and_then(|arr| {
                                            arr.iter().find(|a| {
                                                a.get("kind").and_then(|k| k.as_str()) == Some("git_repo")
                                            })
                                        })
                                        .and_then(|a| a.get("source_ref"))
                                        .and_then(|s| s.as_str())
                                        .unwrap_or_default()
                                        .to_string();
                                    let branch = repo
                                        .get("artifacts")
                                        .and_then(|a| a.as_array())
                                        .and_then(|arr| {
                                            arr.iter().find_map(|a| {
                                                a.get("git")
                                                    .and_then(|g| g.get("default_branch"))
                                                    .and_then(|b| b.as_str())
                                            })
                                        })
                                        .unwrap_or("main")
                                        .to_string();
                                    let findings = repo.get("findings_count").and_then(|n| n.as_u64()).unwrap_or(0);
                                    let findings_label = if findings != 1 { format!("{findings} findings") } else { "1 finding".to_string() };
                                    rsx! {
                                        Link {
                                            to: Route::GraphExplorerPage { repo_id },
                                            class: "graph-repo-card",
                                            div { class: "graph-repo-card-header",
                                                div { class: "graph-repo-card-icon", "\u{29BB}" }
                                                h3 { class: "graph-repo-card-name", "{name}" }
                                            }
                                            if !url.is_empty() {
                                                p { class: "graph-repo-card-url", "{url}" }
                                            }
                                            div { class: "graph-repo-card-meta",
                                                span { class: "graph-repo-card-tag",
                                                    "\u{E0A0} {branch}"
                                                }
                                                span { class: "graph-repo-card-tag graph-repo-card-tag-findings",
                                                    "{findings_label}"
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            Some(None) => rsx! {
                div { class: "card", p { "Failed to load repositories." } }
            },
            None => rsx! {
                div { class: "loading", "Loading repositories..." }
            },
        }
    }
}
