//! Targets page — lists onboarded targets (the unified `OnboardedTarget`
//! records the wizard creates) and lets the user run a scan, inspect the
//! classification / applicable scans, or delete a target.
//!
//! Creation lives in the Onboard wizard (`/onboard`); this page is the
//! "where is my target, and what did the scan find" surface.

use dioxus::prelude::*;
use dioxus_free_icons::icons::bs_icons::*;
use dioxus_free_icons::Icon;

use crate::components::page_header::PageHeader;
use crate::components::toast::{ToastType, Toasts};
use crate::infrastructure::onboarding::{
    delete_target, fetch_applicable_scans, fetch_targets, trigger_target_scan, update_target,
    validate_artifact_ref, validate_target_name, ArtifactInputDto,
};

/// The nine target families (value, label) for the edit form's type selector.
const TARGET_TYPES: &[(&str, &str)] = &[
    ("web_app", "Web Application"),
    ("backend_service", "Backend / API"),
    ("desktop_app", "Desktop App"),
    ("android_app", "Android App"),
    ("ios_app", "iOS App"),
    ("firmware_bare_metal", "Firmware — bare metal"),
    ("firmware_rtos", "Firmware — RTOS"),
    ("embedded_linux_yocto", "Embedded Linux / Yocto"),
    ("plc_sps", "PLC / SPS"),
];

/// The artifact kinds (value, label) for the edit form.
const ARTIFACT_KINDS: &[(&str, &str)] = &[
    ("git_repo", "Git repository"),
    ("source_archive", "Source archive (zip)"),
    ("firmware_image", "Firmware image"),
    ("mobile_package", "Mobile package (APK/IPA)"),
    ("container_image", "Container image"),
    ("live_url", "Live URL"),
    ("plc_project", "PLC project"),
    ("plaintext_description", "Description (text)"),
];

/// Prettify a snake_case target-type value into a human label.
fn pretty_type(v: &str) -> String {
    match v {
        "web_app" => "Web Application".into(),
        "backend_service" => "Backend / API".into(),
        "desktop_app" => "Desktop App".into(),
        "android_app" => "Android App".into(),
        "ios_app" => "iOS App".into(),
        "firmware_bare_metal" => "Firmware — bare metal".into(),
        "firmware_rtos" => "Firmware — RTOS".into(),
        "embedded_linux_yocto" => "Embedded Linux / Yocto".into(),
        "plc_sps" => "PLC / SPS".into(),
        other => other.replace('_', " "),
    }
}

fn str_at<'a>(v: &'a serde_json::Value, key: &str) -> &'a str {
    v.get(key).and_then(|x| x.as_str()).unwrap_or("")
}

fn target_id(t: &serde_json::Value) -> String {
    t.get("_id")
        .and_then(|o| o.get("$oid"))
        .and_then(|s| s.as_str())
        .unwrap_or_default()
        .to_string()
}

/// The applicable-scans matrix for one target, fetched on expand.
#[component]
fn TargetScans(id: String) -> Element {
    let scan_id = id.clone();
    let scans = use_resource(move || {
        let id = scan_id.clone();
        async move { fetch_applicable_scans(id).await.ok() }
    });

    let snapshot = scans.read().clone();
    match &snapshot {
        Some(Some(resp)) => {
            let rows = resp.data.scans.clone();
            let pentest = resp.data.pentest_supported;
            rsx! {
                div { style: "margin-top: 8px;",
                    if rows.is_empty() {
                        div { style: "opacity: 0.6;", "No scans available (no code / URL / firmware artifact present)." }
                    }
                    for s in rows {
                        {
                            let name = str_at(&s, "scan").to_string();
                            let rationale = str_at(&s, "rationale").to_string();
                            let blocked = s.get("blocked_reason").and_then(|b| b.as_str()).map(String::from);
                            let default_on = s.get("default_on").and_then(|b| b.as_bool()).unwrap_or(false);
                            let badge = if blocked.is_some() {
                                "badge badge-info"
                            } else if default_on {
                                "badge badge-success"
                            } else {
                                "badge"
                            };
                            rsx! {
                                div { style: "display: flex; gap: 8px; align-items: center; padding: 4px 0;",
                                    span { class: "{badge}", "{name}" }
                                    span { style: "opacity: 0.8; font-size: 0.9em;", "{rationale}" }
                                    if let Some(b) = blocked {
                                        span { style: "opacity: 0.6; font-style: italic; font-size: 0.9em;", "— {b}" }
                                    }
                                }
                            }
                        }
                    }
                    if pentest {
                        div { style: "margin-top: 6px; opacity: 0.75; font-size: 0.85em;",
                            "Active pentest is supported for this target type."
                        }
                    }
                }
            }
        }
        Some(None) => rsx! { div { style: "opacity: 0.6;", "Failed to load applicable scans." } },
        None => rsx! { div { style: "opacity: 0.6;", "Loading scans..." } },
    }
}

#[component]
pub fn TargetsPage() -> Element {
    let mut toasts = use_context::<Toasts>();
    let mut scanning_ids = use_signal(Vec::<String>::new);
    let mut expanded_ids = use_signal(Vec::<String>::new);
    let mut confirm_delete = use_signal(|| Option::<(String, String)>::None);

    // Edit-target modal state.
    let mut edit_id = use_signal(|| Option::<String>::None);
    let mut edit_name = use_signal(String::new);
    let mut edit_type = use_signal(String::new);
    let mut edit_arts = use_signal(Vec::<ArtifactInputDto>::new);
    let mut edit_saving = use_signal(|| false);
    // In-modal "add artifact" mini-form.
    let mut e_kind = use_signal(|| "git_repo".to_string());
    let mut e_source = use_signal(String::new);
    let mut e_branch = use_signal(|| "main".to_string());

    let mut targets = use_resource(move || async move { fetch_targets().await.ok() });

    rsx! {
        PageHeader {
            title: "Targets",
            description: "Onboarded targets and what their scans found. Add new targets from Onboard.",
        }

        div { style: "margin-bottom: 16px; display: flex; gap: 8px;",
            Link { to: crate::app::Route::OnboardingPage {}, class: "btn btn-primary",
                "+ Onboard a target"
            }
            button {
                class: "btn btn-secondary",
                onclick: move |_| targets.restart(),
                "Refresh"
            }
        }

        // ── Delete confirmation ──
        if let Some((del_id, del_name)) = confirm_delete() {
            div { class: "modal-overlay",
                div { class: "modal-dialog",
                    h3 { "Delete Target" }
                    p { "Delete " strong { "{del_name}" } "?" }
                    p { class: "modal-warning",
                        "This permanently removes the target and its findings, SBOM entries, scan runs, and CVE alerts."
                    }
                    div { class: "modal-actions",
                        button {
                            class: "btn btn-secondary",
                            onclick: move |_| confirm_delete.set(None),
                            "Cancel"
                        }
                        button {
                            class: "btn btn-danger",
                            onclick: move |_| {
                                let id = del_id.clone();
                                let name = del_name.clone();
                                confirm_delete.set(None);
                                spawn(async move {
                                    match delete_target(id).await {
                                        Ok(_) => {
                                            toasts.push(ToastType::Success, format!("{name} deleted"));
                                            targets.restart();
                                        }
                                        Err(e) => toasts.push(ToastType::Error, e.to_string()),
                                    }
                                });
                            },
                            "Delete"
                        }
                    }
                }
            }
        }

        // ── Edit target ──
        if let Some(eid) = edit_id() {
            {
            let name_err = validate_target_name(&edit_name());
            let e_source_err = if e_source().is_empty() {
                None
            } else {
                validate_artifact_ref(&e_kind(), &e_source())
            };
            rsx! {
                div { class: "modal-overlay",
                    div { class: "modal-dialog",
                        h3 { "Edit target" }
                        div { class: "form-group",
                            label { "Name" }
                            input {
                                r#type: "text",
                                value: "{edit_name}",
                                oninput: move |e| edit_name.set(e.value()),
                            }
                            if !edit_name().is_empty() {
                                if let Some(err) = name_err.clone() {
                                    div { style: "color: var(--danger, #d33); font-size: 0.85em;", "{err}" }
                                }
                            }
                        }
                        div { class: "form-group",
                            label { "Type" }
                            select {
                                value: "{edit_type}",
                                oninput: move |e| edit_type.set(e.value()),
                                for (v, l) in TARGET_TYPES.iter().copied() {
                                    option { value: "{v}", selected: edit_type() == v, "{l}" }
                                }
                            }
                        }
                        label { style: "font-weight: 600;", "Artifacts" }
                        for (i, a) in edit_arts().iter().enumerate() {
                            div { style: "display: flex; justify-content: space-between; align-items: center; padding: 4px 0;",
                                span { style: "font-size: 0.9em;",
                                    span { style: "opacity: 0.7;", "{a.kind}: " }
                                    span { style: "font-family: monospace;", "{a.source_ref}" }
                                }
                                button {
                                    class: "btn btn-ghost btn-ghost-danger btn-sm",
                                    onclick: move |_| { edit_arts.write().remove(i); },
                                    "Remove"
                                }
                            }
                        }
                        div { style: "display: flex; gap: 8px; align-items: flex-end; margin-top: 8px;",
                            div { class: "form-group", style: "margin: 0;",
                                label { "Kind" }
                                select {
                                    value: "{e_kind}",
                                    oninput: move |e| e_kind.set(e.value()),
                                    for (v, l) in ARTIFACT_KINDS.iter().copied() {
                                        option { value: "{v}", selected: e_kind() == v, "{l}" }
                                    }
                                }
                            }
                            div { class: "form-group", style: "margin: 0; flex: 1;",
                                label { "Reference" }
                                input {
                                    r#type: "text",
                                    value: "{e_source}",
                                    oninput: move |e| e_source.set(e.value()),
                                }
                            }
                            if e_kind() == "git_repo" {
                                div { class: "form-group", style: "margin: 0;",
                                    label { "Branch" }
                                    input {
                                        r#type: "text",
                                        value: "{e_branch}",
                                        oninput: move |e| e_branch.set(e.value()),
                                    }
                                }
                            }
                            button {
                                class: "btn btn-secondary",
                                disabled: e_source().trim().is_empty() || e_source_err.is_some(),
                                onclick: move |_| {
                                    let kind = e_kind();
                                    if !e_source().trim().is_empty()
                                        && validate_artifact_ref(&kind, &e_source()).is_none()
                                    {
                                        let branch = if kind == "git_repo" { Some(e_branch()) } else { None };
                                        edit_arts.write().push(ArtifactInputDto {
                                            kind,
                                            source_ref: e_source(),
                                            branch,
                                            plc_format: None,
                                        });
                                        e_source.set(String::new());
                                    }
                                },
                                "+ Add"
                            }
                        }
                        if let Some(err) = e_source_err.clone() {
                            div { style: "color: var(--danger, #d33); font-size: 0.85em;", "{err}" }
                        }
                        div { class: "modal-actions",
                            button {
                                class: "btn btn-secondary",
                                onclick: move |_| edit_id.set(None),
                                "Cancel"
                            }
                            button {
                                class: "btn btn-primary",
                                disabled: edit_saving() || name_err.is_some(),
                                onclick: move |_| {
                                    let id = eid.clone();
                                    let nm = edit_name();
                                    let tt = edit_type();
                                    let arts = edit_arts();
                                    edit_saving.set(true);
                                    spawn(async move {
                                        match update_target(id, Some(nm), Some(tt), Some(arts)).await {
                                            Ok(_) => {
                                                toasts.push(ToastType::Success, "Target updated");
                                                targets.restart();
                                                edit_id.set(None);
                                            }
                                            Err(e) => toasts.push(ToastType::Error, e.to_string()),
                                        }
                                        edit_saving.set(false);
                                    });
                                },
                                if edit_saving() { "Saving..." } else { "Save" }
                            }
                        }
                    }
                }
            }
            }
        }

        {
        let targets_snapshot = targets.read().clone();
        match &targets_snapshot {
            Some(Some(resp)) => {
                let rows = resp.data.clone();
                if rows.is_empty() {
                    rsx! {
                        div { class: "card", style: "padding: 24px; text-align: center;",
                            p { style: "opacity: 0.7;", "No targets yet." }
                            Link { to: crate::app::Route::OnboardingPage {}, class: "btn btn-primary",
                                "Onboard your first target"
                            }
                        }
                    }
                } else {
                    rsx! {
                        div { class: "card",
                            div { class: "table-wrapper",
                                table {
                                    thead {
                                        tr {
                                            th { "Name" }
                                            th { "Type" }
                                            th { "Detected" }
                                            th { "Artifacts" }
                                            th { "Findings" }
                                            th { "Actions" }
                                        }
                                    }
                                    tbody {
                                        for t in rows {
                                            {
                                                let id = target_id(&t);
                                                let name = str_at(&t, "name").to_string();
                                                let ttype = pretty_type(str_at(&t, "target_type"));
                                                let suggested = t
                                                    .get("classification")
                                                    .and_then(|c| c.get("suggested"))
                                                    .and_then(|s| s.as_str())
                                                    .map(pretty_type);
                                                let artifacts = t
                                                    .get("artifacts")
                                                    .and_then(|a| a.as_array())
                                                    .cloned()
                                                    .unwrap_or_default();
                                                let findings = t
                                                    .get("findings_count")
                                                    .and_then(|n| n.as_u64())
                                                    .unwrap_or(0);
                                                let facts = t
                                                    .get("classification")
                                                    .and_then(|c| c.get("facts"))
                                                    .and_then(|f| f.as_array())
                                                    .cloned()
                                                    .unwrap_or_default();
                                                let is_scanning = scanning_ids().contains(&id);
                                                let is_expanded = expanded_ids().contains(&id);
                                                let id_scan = id.clone();
                                                let id_exp = id.clone();
                                                let id_del = id.clone();
                                                let id_edit = id.clone();
                                                let name_del = name.clone();
                                                let name_edit = name.clone();
                                                let ttype_raw = str_at(&t, "target_type").to_string();
                                                let artifacts_detail = artifacts.clone();
                                                let artifacts_edit = artifacts.clone();
                                                rsx! {
                                                    tr {
                                                        td { strong { "{name}" } }
                                                        td { "{ttype}" }
                                                        td {
                                                            if let Some(sug) = suggested.clone() {
                                                                span { class: "badge badge-success", "{sug}" }
                                                            } else {
                                                                span { style: "opacity: 0.5;", "—" }
                                                            }
                                                        }
                                                        td { "{artifacts.len()}" }
                                                        td { "{findings}" }
                                                        td { style: "display: flex; gap: 4px;",
                                                            button {
                                                                class: "btn btn-ghost",
                                                                title: "Details",
                                                                onclick: move |_| {
                                                                    let mut ids = expanded_ids();
                                                                    if ids.contains(&id_exp) {
                                                                        ids.retain(|i| i != &id_exp);
                                                                    } else {
                                                                        ids.push(id_exp.clone());
                                                                    }
                                                                    expanded_ids.set(ids);
                                                                },
                                                                Icon { icon: BsInfoCircle, width: 16, height: 16 }
                                                            }
                                                            button {
                                                                class: "btn btn-ghost",
                                                                title: "Edit target",
                                                                onclick: move |_| {
                                                                    edit_name.set(name_edit.clone());
                                                                    edit_type.set(ttype_raw.clone());
                                                                    let arts: Vec<ArtifactInputDto> = artifacts_edit
                                                                        .iter()
                                                                        .map(|a| ArtifactInputDto {
                                                                            kind: str_at(a, "kind").to_string(),
                                                                            source_ref: str_at(a, "source_ref").to_string(),
                                                                            branch: a
                                                                                .get("git")
                                                                                .and_then(|g| g.get("default_branch"))
                                                                                .and_then(|b| b.as_str())
                                                                                .map(String::from),
                                                                            plc_format: None,
                                                                        })
                                                                        .collect();
                                                                    edit_arts.set(arts);
                                                                    e_source.set(String::new());
                                                                    edit_id.set(Some(id_edit.clone()));
                                                                },
                                                                Icon { icon: BsPencil, width: 16, height: 16 }
                                                            }
                                                            button {
                                                                class: if is_scanning { "btn btn-ghost btn-scanning" } else { "btn btn-ghost" },
                                                                title: "Run scan",
                                                                disabled: is_scanning,
                                                                onclick: move |_| {
                                                                    let id = id_scan.clone();
                                                                    let mut ids = scanning_ids();
                                                                    ids.push(id.clone());
                                                                    scanning_ids.set(ids);
                                                                    spawn(async move {
                                                                        match trigger_target_scan(id.clone()).await {
                                                                            Ok(_) => toasts.push(ToastType::Success, "Scan triggered — findings appear as it runs. Use Refresh."),
                                                                            Err(e) => toasts.push(ToastType::Error, e.to_string()),
                                                                        }
                                                                        let mut ids = scanning_ids();
                                                                        ids.retain(|i| i != &id);
                                                                        scanning_ids.set(ids);
                                                                    });
                                                                },
                                                                if is_scanning {
                                                                    span { class: "spinner" }
                                                                } else {
                                                                    Icon { icon: BsPlayCircle, width: 16, height: 16 }
                                                                }
                                                            }
                                                            button {
                                                                class: "btn btn-ghost btn-ghost-danger",
                                                                title: "Delete target",
                                                                onclick: move |_| {
                                                                    confirm_delete.set(Some((id_del.clone(), name_del.clone())));
                                                                },
                                                                Icon { icon: BsTrash, width: 16, height: 16 }
                                                            }
                                                        }
                                                    }
                                                    if is_expanded {
                                                        tr {
                                                            td { colspan: "6",
                                                                div { style: "padding: 12px 8px;",
                                                                    h4 { style: "margin: 0 0 6px;", "Artifacts" }
                                                                    if artifacts_detail.is_empty() {
                                                                        div { style: "opacity: 0.6;", "No artifacts." }
                                                                    }
                                                                    for a in artifacts_detail {
                                                                        div { style: "font-size: 0.9em; padding: 2px 0;",
                                                                            span { style: "opacity: 0.7;", "{str_at(&a, \"kind\")}: " }
                                                                            span { style: "font-family: monospace;", "{str_at(&a, \"source_ref\")}" }
                                                                        }
                                                                    }
                                                                    if !facts.is_empty() {
                                                                        h4 { style: "margin: 12px 0 6px;", "Detected facts" }
                                                                        for f in facts {
                                                                            div { style: "font-size: 0.9em; padding: 2px 0;",
                                                                                span { style: "font-family: monospace;", "{str_at(&f, \"key\")}={str_at(&f, \"value\")}" }
                                                                                span { style: "opacity: 0.5;", " ({str_at(&f, \"source\")})" }
                                                                            }
                                                                        }
                                                                    }
                                                                    h4 { style: "margin: 12px 0 6px;", "Applicable scans" }
                                                                    TargetScans { id: id.clone() }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Some(None) => rsx! {
                div { class: "card", p { "Failed to load targets." } }
            },
            None => rsx! {
                div { class: "loading", "Loading targets..." }
            },
        }
        }
    }
}
