//! Tasks view implementation.

use uuid::Uuid;

use crate::daemon::api::ApiClient;
use crate::daemon::tui::app::ListItem;

/// Load tasks from API
pub async fn load_tasks(
    client: &ApiClient,
    contract_id: Option<Uuid>,
) -> Result<Vec<ListItem>, Box<dyn std::error::Error>> {
    let Some(contract_id) = contract_id else {
        // TODO: Implement listing all tasks across contracts
        return Ok(Vec::new());
    };

    let result = client.supervisor_tasks(contract_id).await?;

    // Parse JSON response into ListItem
    let tasks: Vec<serde_json::Value> = serde_json::from_value(result.0)?;

    let items = tasks
        .into_iter()
        .filter_map(|t| {
            let id_str = t.get("id")?.as_str()?;
            let id = Uuid::parse_str(id_str).ok()?;

            Some(ListItem {
                id,
                name: t
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or("Unnamed")
                    .to_string(),
                status: t.get("status").and_then(|v| v.as_str()).map(String::from),
                description: t
                    .get("progressSummary")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                updated_at: t
                    .get("updatedAt")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                extra: t,
            })
        })
        .collect();

    Ok(items)
}

/// Get full task details for preview
pub async fn get_task_preview(
    client: &ApiClient,
    task_id: Uuid,
) -> Result<String, Box<dyn std::error::Error>> {
    let result = client.supervisor_get_task(task_id).await?;
    let task: serde_json::Value = result.0;

    Ok(format!(
        "Name: {}\nStatus: {}\nPlan: {}\n\nProgress:\n{}",
        task.get("name").and_then(|v| v.as_str()).unwrap_or("-"),
        task.get("status").and_then(|v| v.as_str()).unwrap_or("-"),
        task.get("plan").and_then(|v| v.as_str()).unwrap_or("-"),
        task.get("progressSummary")
            .and_then(|v| v.as_str())
            .unwrap_or("-"),
    ))
}
