use comfy_table::{presets::UTF8_FULL, ContentArrangement, Table};
use owo_colors::OwoColorize;

use crate::AnalysisResult;

pub fn render(result: &AnalysisResult) {
    let matched: Vec<_> = result.variants.iter().filter(|v| v.matched.is_some()).collect();
    let unmatched: Vec<_> = result.variants.iter().filter(|v| v.matched.is_none()).collect();

    if !matched.is_empty() {
        println!("\n  {} Genetic Variant Analysis\n", "labgenetics".bold());

        let mut table = Table::new();
        table.load_preset(UTF8_FULL);
        table.set_content_arrangement(ContentArrangement::Dynamic);
        table.set_header(vec![
            "Gene", "Variant", "Category", "Risk", "Pathogenicity", "Actionable",
        ]);

        for v in &matched {
            let m = v.matched.as_ref().unwrap();
            let risk_colored = match v.risk_level.as_str() {
                "high" => v.risk_level.red().to_string(),
                "moderate" => v.risk_level.yellow().to_string(),
                "carrier" => v.risk_level.cyan().to_string(),
                "low" | "benign" => v.risk_level.green().to_string(),
                _ => v.risk_level.clone(),
            };
            let actionable = if m.actionable {
                "Yes".green().to_string()
            } else {
                "No".dimmed().to_string()
            };

            table.add_row(vec![
                m.gene.clone(),
                m.variant_name.clone(),
                m.category.clone(),
                risk_colored,
                m.pathogenicity.clone(),
                actionable,
            ]);
        }

        println!("{table}");

        // Show actions for actionable variants
        for v in &matched {
            if !v.actions.is_empty() {
                let m = v.matched.as_ref().unwrap();
                println!(
                    "\n  {} {} {}:",
                    "→".bold(),
                    m.gene.bold(),
                    m.variant_name
                );
                for action in &v.actions {
                    println!("    • {action}");
                }
            }
        }

        // Show PGx results
        let pgx_results: Vec<_> = matched.iter().filter(|v| v.pgx.is_some()).collect();
        if !pgx_results.is_empty() {
            println!("\n  {} Pharmacogenomics\n", "⚕".bold());
            for v in pgx_results {
                let pgx = v.pgx.as_ref().unwrap();
                println!(
                    "  {} {}: {} — {}",
                    "→".bold(),
                    pgx.gene.bold(),
                    pgx.phenotype,
                    pgx.recommendation
                );
                if !pgx.affected_drugs.is_empty() {
                    println!("    Affected drugs: {}", pgx.affected_drugs.join(", "));
                }
            }
        }
    }

    if !unmatched.is_empty() {
        println!(
            "\n  {} Unmatched ({}):",
            "⚠".yellow(),
            unmatched.len()
        );
        for v in &unmatched {
            let id = if v.input.gene.is_empty() {
                v.input.id.clone()
            } else {
                format!("{} {}", v.input.gene, v.input.common_name)
            };
            println!("    • {id}");
        }
    }

    let unmatched_str = unmatched.len().to_string();
    let unmatched_colored = if unmatched.is_empty() {
        unmatched_str.green().to_string()
    } else {
        unmatched_str.yellow().to_string()
    };

    println!(
        "\n  {} matched, {} unmatched out of {} input variants\n",
        matched.len().to_string().green(),
        unmatched_colored,
        result.total_input,
    );
}
