use std::collections::HashMap;
use crate::types::LoadTestOutput;

pub fn generate_html_report(
    results: &HashMap<String, LoadTestOutput>,
    title: &str,
) -> String {
    let mut datasets_throughput = Vec::new();
    let mut datasets_success = Vec::new();
    let mut datasets_p50 = Vec::new();
    let mut datasets_p99 = Vec::new();
    let mut labels = Vec::new();

    let colors = [
        "rgb(59, 130, 246)",
        "rgb(239, 68, 68)",
        "rgb(34, 197, 94)",
        "rgb(168, 85, 247)",
        "rgb(249, 115, 22)",
        "rgb(20, 184, 166)",
    ];

    for (i, (name, output)) in results.iter().enumerate() {
        let color = colors[i % colors.len()];

        if labels.is_empty() {
            labels = output.target_rate.iter().map(|r| r.to_string()).collect();
        }

        datasets_throughput.push(format!(
            r#"{{
                label: '{}',
                data: [{}],
                borderColor: '{}',
                backgroundColor: '{}',
                tension: 0.1
            }}"#,
            name,
            output.throughput.iter()
                .map(|v| v.map(|x| format!("{:.1}", x)).unwrap_or_else(|| "null".to_string()))
                .collect::<Vec<_>>().join(", "),
            color,
            color.replace("rgb", "rgba").replace(")", ", 0.1)")
        ));

        datasets_success.push(format!(
            r#"{{
                label: '{}',
                data: [{}],
                borderColor: '{}',
                backgroundColor: '{}',
                tension: 0.1
            }}"#,
            name,
            output.success.iter()
                .map(|v| v.map(|x| format!("{:.1}", x * 100.0)).unwrap_or_else(|| "null".to_string()))
                .collect::<Vec<_>>().join(", "),
            color,
            color.replace("rgb", "rgba").replace(")", ", 0.1)")
        ));

        datasets_p50.push(format!(
            r#"{{
                label: '{}',
                data: [{}],
                borderColor: '{}',
                backgroundColor: '{}',
                tension: 0.1
            }}"#,
            name,
            output.p50.iter()
                .map(|v| v.map(|x| format!("{:.2}", x * 1000.0)).unwrap_or_else(|| "null".to_string()))
                .collect::<Vec<_>>().join(", "),
            color,
            color.replace("rgb", "rgba").replace(")", ", 0.1)")
        ));

        datasets_p99.push(format!(
            r#"{{
                label: '{}',
                data: [{}],
                borderColor: '{}',
                backgroundColor: '{}',
                tension: 0.1
            }}"#,
            name,
            output.p99.iter()
                .map(|v| v.map(|x| format!("{:.2}", x * 1000.0)).unwrap_or_else(|| "null".to_string()))
                .collect::<Vec<_>>().join(", "),
            color,
            color.replace("rgb", "rgba").replace(")", ", 0.1)")
        ));
    }

    let labels_json = labels.iter().map(|l| format!("'{}'", l)).collect::<Vec<_>>().join(", ");

    let mut table_rows = String::new();
    for (name, output) in results {
        for i in 0..output.target_rate.len() {
            table_rows.push_str(&format!(
                r#"<tr>
                    <td>{}</td>
                    <td>{}</td>
                    <td>{}</td>
                    <td>{}</td>
                    <td>{}</td>
                    <td>{}</td>
                    <td>{}</td>
                    <td>{}</td>
                </tr>"#,
                name,
                output.target_rate.get(i).map(|v| v.to_string()).unwrap_or_default(),
                output.throughput.get(i).and_then(|v| *v).map(|v| format!("{:.1}", v)).unwrap_or_else(|| "-".into()),
                output.success.get(i).and_then(|v| *v).map(|v| format!("{:.1}%", v * 100.0)).unwrap_or_else(|| "-".into()),
                output.p50.get(i).and_then(|v| *v).map(|v| format!("{:.2}ms", v * 1000.0)).unwrap_or_else(|| "-".into()),
                output.p90.get(i).and_then(|v| *v).map(|v| format!("{:.2}ms", v * 1000.0)).unwrap_or_else(|| "-".into()),
                output.p95.get(i).and_then(|v| *v).map(|v| format!("{:.2}ms", v * 1000.0)).unwrap_or_else(|| "-".into()),
                output.p99.get(i).and_then(|v| *v).map(|v| format!("{:.2}ms", v * 1000.0)).unwrap_or_else(|| "-".into()),
            ));
        }
    }

    format!(
        r##"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title} - Aqua Report</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #0f172a;
            color: #e2e8f0;
            padding: 2rem;
            line-height: 1.6;
        }}
        .container {{ max-width: 1400px; margin: 0 auto; }}
        h1 {{
            font-size: 2rem;
            margin-bottom: 0.5rem;
            color: #f8fafc;
        }}
        .subtitle {{
            color: #94a3b8;
            margin-bottom: 2rem;
        }}
        .grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }}
        .card {{
            background: #1e293b;
            border-radius: 12px;
            padding: 1.5rem;
            border: 1px solid #334155;
        }}
        .card h2 {{
            font-size: 1rem;
            color: #94a3b8;
            margin-bottom: 1rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }}
        .chart-container {{
            position: relative;
            height: 300px;
        }}
        table {{
            width: 100%;
            border-collapse: collapse;
            font-size: 0.875rem;
        }}
        th, td {{
            padding: 0.75rem 1rem;
            text-align: left;
            border-bottom: 1px solid #334155;
        }}
        th {{
            color: #94a3b8;
            font-weight: 500;
            text-transform: uppercase;
            font-size: 0.75rem;
            letter-spacing: 0.05em;
        }}
        tr:hover {{ background: #334155; }}
        .footer {{
            margin-top: 2rem;
            padding-top: 1rem;
            border-top: 1px solid #334155;
            color: #64748b;
            font-size: 0.875rem;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>🌊 {title}</h1>
        <p class="subtitle">Load Test Report - Generated by Aqua</p>

        <div class="grid">
            <div class="card">
                <h2>Throughput vs Load</h2>
                <div class="chart-container">
                    <canvas id="throughputChart"></canvas>
                </div>
            </div>
            <div class="card">
                <h2>Success Rate vs Load</h2>
                <div class="chart-container">
                    <canvas id="successChart"></canvas>
                </div>
            </div>
            <div class="card">
                <h2>P50 Latency vs Load</h2>
                <div class="chart-container">
                    <canvas id="p50Chart"></canvas>
                </div>
            </div>
            <div class="card">
                <h2>P99 Latency vs Load</h2>
                <div class="chart-container">
                    <canvas id="p99Chart"></canvas>
                </div>
            </div>
        </div>

        <div class="card">
            <h2>Detailed Results</h2>
            <table>
                <thead>
                    <tr>
                        <th>Node</th>
                        <th>Target RPS</th>
                        <th>Throughput</th>
                        <th>Success</th>
                        <th>P50</th>
                        <th>P90</th>
                        <th>P95</th>
                        <th>P99</th>
                    </tr>
                </thead>
                <tbody>
                    {table_rows}
                </tbody>
            </table>
        </div>

        <div class="footer">
            Generated by <a href="https://github.com/sarthakdev/aqua" style="color: #60a5fa;">Aqua</a>
        </div>
    </div>

    <script>
        const chartOptions = {{
            responsive: true,
            maintainAspectRatio: false,
            plugins: {{
                legend: {{
                    position: 'bottom',
                    labels: {{ color: '#94a3b8' }}
                }}
            }},
            scales: {{
                x: {{
                    title: {{ display: true, text: 'Target RPS', color: '#94a3b8' }},
                    grid: {{ color: '#334155' }},
                    ticks: {{ color: '#94a3b8' }}
                }},
                y: {{
                    grid: {{ color: '#334155' }},
                    ticks: {{ color: '#94a3b8' }}
                }}
            }}
        }};

        new Chart(document.getElementById('throughputChart'), {{
            type: 'line',
            data: {{
                labels: [{labels_json}],
                datasets: [{datasets_throughput}]
            }},
            options: {{
                ...chartOptions,
                scales: {{
                    ...chartOptions.scales,
                    y: {{ ...chartOptions.scales.y, title: {{ display: true, text: 'Actual RPS', color: '#94a3b8' }} }}
                }}
            }}
        }});

        new Chart(document.getElementById('successChart'), {{
            type: 'line',
            data: {{
                labels: [{labels_json}],
                datasets: [{datasets_success}]
            }},
            options: {{
                ...chartOptions,
                scales: {{
                    ...chartOptions.scales,
                    y: {{ ...chartOptions.scales.y, title: {{ display: true, text: 'Success %', color: '#94a3b8' }}, min: 0, max: 100 }}
                }}
            }}
        }});

        new Chart(document.getElementById('p50Chart'), {{
            type: 'line',
            data: {{
                labels: [{labels_json}],
                datasets: [{datasets_p50}]
            }},
            options: {{
                ...chartOptions,
                scales: {{
                    ...chartOptions.scales,
                    y: {{ ...chartOptions.scales.y, title: {{ display: true, text: 'Latency (ms)', color: '#94a3b8' }} }}
                }}
            }}
        }});

        new Chart(document.getElementById('p99Chart'), {{
            type: 'line',
            data: {{
                labels: [{labels_json}],
                datasets: [{datasets_p99}]
            }},
            options: {{
                ...chartOptions,
                scales: {{
                    ...chartOptions.scales,
                    y: {{ ...chartOptions.scales.y, title: {{ display: true, text: 'Latency (ms)', color: '#94a3b8' }} }}
                }}
            }}
        }});
    </script>
</body>
</html>"##,
        title = title,
        table_rows = table_rows,
        labels_json = labels_json,
        datasets_throughput = datasets_throughput.join(",\n                "),
        datasets_success = datasets_success.join(",\n                "),
        datasets_p50 = datasets_p50.join(",\n                "),
        datasets_p99 = datasets_p99.join(",\n                "),
    )
}
