use dioxus::prelude::*;
use serde::{Deserialize, Serialize};

use compliance_core::models::Finding;

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FindingsListResponse {
    pub data: Vec<Finding>,
    pub total: Option<u64>,
    pub page: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FindingsQuery {
    pub page: u64,
    pub severity: String,
    pub scan_type: String,
    pub status: String,
    pub repo_id: String,
    pub q: String,
    pub sort_by: String,
    pub sort_order: String,
}

#[server]
pub async fn fetch_findings(query: FindingsQuery) -> Result<FindingsListResponse, ServerFnError> {
    let mut path = format!("/api/v1/findings?page={}&limit=20", query.page);
    if !query.severity.is_empty() {
        path.push_str(&format!("&severity={}", query.severity));
    }
    if !query.scan_type.is_empty() {
        path.push_str(&format!("&scan_type={}", query.scan_type));
    }
    if !query.status.is_empty() {
        path.push_str(&format!("&status={}", query.status));
    }
    if !query.repo_id.is_empty() {
        path.push_str(&format!("&repo_id={}", query.repo_id));
    }
    if !query.q.is_empty() {
        path.push_str(&format!(
            "&q={}",
            url::form_urlencoded::byte_serialize(query.q.as_bytes()).collect::<String>()
        ));
    }
    if !query.sort_by.is_empty() {
        path.push_str(&format!("&sort_by={}", query.sort_by));
    }
    if !query.sort_order.is_empty() {
        path.push_str(&format!("&sort_order={}", query.sort_order));
    }

    let resp = super::agent_client::agent_get(&path)
        .await?
        .send()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    let body: FindingsListResponse = resp
        .json()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(body)
}

#[server]
pub async fn fetch_finding_detail(id: String) -> Result<Finding, ServerFnError> {
    let resp = super::agent_client::agent_get(&format!("/api/v1/findings/{id}"))
        .await?
        .send()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    let body: serde_json::Value = resp
        .json()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    let finding: Finding = serde_json::from_value(body["data"].clone())
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(finding)
}

#[server]
pub async fn update_finding_status(id: String, status: String) -> Result<(), ServerFnError> {
    super::agent_client::agent_request(
        reqwest::Method::PATCH,
        &format!("/api/v1/findings/{id}/status"),
    )
    .await?
    .json(&serde_json::json!({ "status": status }))
    .send()
    .await
    .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(())
}

#[server]
pub async fn bulk_update_finding_status(
    ids: Vec<String>,
    status: String,
) -> Result<(), ServerFnError> {
    super::agent_client::agent_request(reqwest::Method::PATCH, "/api/v1/findings/bulk-status")
        .await?
        .json(&serde_json::json!({ "ids": ids, "status": status }))
        .send()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(())
}

#[server]
pub async fn update_finding_feedback(id: String, feedback: String) -> Result<(), ServerFnError> {
    super::agent_client::agent_request(
        reqwest::Method::PATCH,
        &format!("/api/v1/findings/{id}/feedback"),
    )
    .await?
    .json(&serde_json::json!({ "feedback": feedback }))
    .send()
    .await
    .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(())
}
