use gloo_net::http::Request;
use leptos::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub api: ApiConfig,
    pub ui: UiConfig,
    pub features: Features,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiConfig {
    pub orchestrator_url: String,
    pub control_center_url: String,
    pub timeout_ms: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiConfig {
    pub theme: String,
    pub page_size: u32,
    pub enable_debug: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Features {
    pub enable_auth: bool,
    pub enable_workflows: bool,
    pub enable_notifications: bool,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            api: ApiConfig {
                orchestrator_url: "http://localhost:8080".to_string(),
                control_center_url: "http://localhost:8081".to_string(),
                timeout_ms: 30000,
            },
            ui: UiConfig {
                theme: "auto".to_string(),
                page_size: 20,
                enable_debug: false,
            },
            features: Features {
                enable_auth: false,
                enable_workflows: true,
                enable_notifications: true,
            },
        }
    }
}

/// Load configuration from control-center API
/// Config is loaded from workspace TOML files by control-center
pub async fn load_config() -> Config {
    // Fetch config from control-center API (workspace TOML-based)
    match Request::get("/api/config").send().await {
        Ok(response) => {
            if response.ok() {
                match response.json::<Config>().await {
                    Ok(config) => {
                        web_sys::console::log_1(
                            &"✅ Config loaded from API (workspace TOML)".into(),
                        );
                        config
                    }
                    Err(e) => {
                        web_sys::console::warn_1(
                            &format!("⚠️ Failed to parse API config: {}, using defaults", e).into(),
                        );
                        Config::default()
                    }
                }
            } else {
                web_sys::console::warn_1(
                    &"⚠️ API config endpoint not available, using defaults".into(),
                );
                Config::default()
            }
        }
        Err(e) => {
            web_sys::console::warn_1(
                &format!("⚠️ Failed to fetch API config: {}, using defaults", e).into(),
            );
            Config::default()
        }
    }
}

use std::cell::RefCell;

thread_local! {
    /// Global config signal - to be initialized at app startup
    static CONFIG_SIGNAL: RefCell<Option<RwSignal<Config>>> = const { RefCell::new(None) };
}

/// Initialize the global config
pub fn init_config(config: Config) {
    CONFIG_SIGNAL.with(|signal| {
        *signal.borrow_mut() = Some(RwSignal::new(config));
    });
}

/// Get the current config
pub fn use_config() -> Config {
    CONFIG_SIGNAL.with(|signal| {
        signal
            .borrow()
            .as_ref()
            .map(|s| s.get())
            .unwrap_or_else(Config::default)
    })
}

/// API endpoints
pub mod endpoints {
    pub const HEALTH: &str = "/health";
    pub const TASKS: &str = "/tasks";
    pub const WORKFLOWS: &str = "/workflows";
    pub const WORKFLOWS_LIST: &str = "/workflows/list";
    pub const WORKFLOWS_STATS: &str = "/workflows/stats";

    // IaC Detection endpoints
    pub const DETECTIONS: &str = "/api/iac/detections";
    pub const DETECTIONS_BY_ID: &str = "/api/iac/detections/:id";
    pub const ANALYZE_PROJECT: &str = "/api/iac/detections/analyze";

    // IaC Rules endpoints
    pub const RULES: &str = "/api/iac/rules";
    pub const RULES_BY_ID: &str = "/api/iac/rules/:id";
    pub const RULES_BY_ORG: &str = "/api/iac/rules/org/:org";

    // IaC Deployment endpoints
    pub const DEPLOYMENTS: &str = "/api/iac/deployments";
    pub const DEPLOYMENTS_BY_ID: &str = "/api/iac/deployments/:id";
    pub const DEPLOYMENTS_SUBMIT: &str = "/api/iac/deployments/:id/submit";
    pub const DEPLOYMENTS_STATUS: &str = "/api/iac/deployments/:id/status";
}
