{% extends "base.html" %}

{% block title %}Assessment Report - {{ assessment.name }}{% endblock %}

{% block content %}
    <style>
        .chart-container {
            position: relative;
            height: 60vh; /* Make chart larger on screen */
            max-width: 900px;
            margin: auto;
        }
        @media print {
            .no-print { display: none !important; }
            .chart-container {
                height: 5.8in; /* Half of A4 height for printing */
                width: 100%;
                page-break-inside: avoid;
            }
        }
    </style>
    <div class="container mt-4">
        <div class="card">
            <div class="card-header bg-success text-white">
                <h1 class="card-title mb-0">Assessment Completed!</h1>
            </div>
            <div class="card-body">
                {% if current_user.is_authenticated and current_user.role in ['admin', 'consultant'] %}
                <div class="d-flex justify-content-end mb-3 no-print">
                    <button class="btn btn-secondary mr-2" onclick="window.print()"><i class="fas fa-print"></i> Print</button>
                    
                    <!-- Hidden form for Word download with chart image -->
                    <form id="word-download-form" action="{{ url_for('main.download_word_report', assignment_id=assignment.id) }}" method="POST" style="display: inline;">
                        <input type="hidden" name="chart_image" id="chart-image-input">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-file-word"></i> Download Word</button>
                    </form>
                    
                    
                </div>
                {% endif %}

                <h4 class="mb-3">Client Information</h4>
                <div class="row mb-4">
                    <div class="col-md-4"><strong>Name:</strong> {{ taker_display_name }}</div>
                    <div class="col-md-4"><strong>Age:</strong> {{ taker_display_age }}</div>
                    <div class="col-md-4"><strong>Gender:</strong> {{ taker_display_gender }}</div>
                </div>
                <hr>

                <p class="lead">The results for the <strong>{{ assessment.name }}</strong> assessment have been recorded.</p>

                {% if (current_user.is_authenticated and current_user.role in ['admin', 'consultant']) or is_free %}
                    {% set assessment_name = assessment.name | lower | trim %}

                    {# ISAA Summary #}
                    {% if 'isaa' in assessment_name and summary %}
                        <h3 class="mt-4">ISAA Summary</h3>
                        <div class="alert alert-info">
                            {{ summary|safe }}
                        </div>
                    {% endif %}

                    {# Overall Score for non-VSMS assessments #}
                    <!-- DEBUG: assessment.name='{{ assessment.name }}', assessment_name='{{ assessment_name }}' -->
                    {% if 'vsms' not in assessment_name and 'social maturity' not in assessment_name %}
                        <h3 class="mt-4">Overall Score</h3>
                        {% if 'vadrs' in assessment_name %}
                            {% if interpretation %}
                                <ul>
                                    {% for item in interpretation %}
                                        <li>{{ item }}</li>
                                    {% endfor %}
                                </ul>
                            {% else %}
                                <p>No subtype criteria met.</p>
                            {% endif %}
                        {% elif 'cars' in assessment_name %}
                            <p><strong>Total Raw Score:</strong> {{ total_raw_score }}</p>
                            <p><strong>Interpretation:</strong> {{ interpretation }}</p>
                        {% elif 'dst' in assessment_name or 'ddst' in assessment_name or 'dsst' in assessment_name or 'developmental screening' in assessment_name or 'developmental screening' in assessment.name.lower() %}
                            <p><strong>Total Score (days):</strong> {{ total_raw_score }}</p>
                            {% if interpretation is not none %}
                                <p><strong>Interpretation:</strong> {{ interpretation }}</p>
                            {% endif %}
                        {% else %}
                            <p><strong>Total Raw Score:</strong> {{ total_raw_score }}</p>
                            {% if t_score is not none %}
                                <p><strong>T-Score:</strong> {{ t_score }}</p>
                            {% endif %}
                            {% if interpretation is not none %}
                                <p><strong>Interpretation:</strong> {{ interpretation }}</p>
                            {% endif %}
                        {% endif %}
                        {% if 'isaa' in assessment_name %}
                            {% set isaa_class = 'No Autism' if total_raw_score < 70 else ('Mild Autism' if total_raw_score <= 106 else ('Moderate Autism' if total_raw_score <= 153 else 'Severe Autism')) %}
                            <div class="mt-3">
                                <p><strong>ISAA Classification:</strong> <span class="badge badge-primary" style="font-size: 1.0rem;">{{ isaa_class }}</span></p>
                                <table class="table table-bordered table-sm">
                                    <thead class="thead-light">
                                        <tr>
                                            <th>Classification</th>
                                            <th>No Autism &lt; 70</th>
                                            <th>Mild Autism 70 to 106</th>
                                            <th>Moderate Autism 107 to 153</th>
                                            <th>Severe Autism &gt; 153</th>
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                        {% endif %}
                    {% endif %}

                    {# Domain-wise results #}
                    {% if domain_scores and 'gad 7' not in assessment_name and 'cars' not in assessment_name and 'level 2 anxiety adult' not in assessment_name %}
                        {% if 'cbcl' in assessment_name %}
                        <h3 class="mt-4">CBCL 1.5-5 Domain-wise Results</h3>
                        {% else %}
                        <h3 class="mt-4">Domain-wise Results</h3>
                        {% endif %}
                        <table class="table table-bordered table-striped">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Domain</th>
                                    {% if 'vsms' in assessment_name or 'social maturity' in assessment_name %}
                                        <th>Equivalent Age (Months)</th>
                                    {% elif 'dst' in assessment_name or 'ddst' in assessment_name or 'dsst' in assessment_name or 'developmental screening' in assessment_name %}
                                        <th>Score (days)</th>
                                        <th>Equivalent Age (Months)</th>
                                    {% elif 'vadrs' in assessment_name %}
                                        <th>Score</th>
                                    {% else %}
                                        <th>Score</th>
                                    {% endif %}
                                    {% if 'cbcl' in assessment_name and cbcl_domain_interpretations %}
                                        <th>Interpretation</th>
                                    {% endif %}
                                </tr>
                            </thead>
                            <tbody>
                                {% for domain, score in domain_scores.items() %}
                                    <tr class="{{ 'table-primary font-weight-bold' if 'vadrs' in assessment_name and domain == 'Combined Score' }}">
                                        <td>{{ domain }}</td>
                                        {% if 'vsms' in assessment_name or 'social maturity' in assessment_name %}
                                            <td>{{ "%.2f"|format(score / 30) }}</td>
                                        {% elif 'dst' in assessment_name or 'ddst' in assessment_name or 'dsst' in assessment_name or 'developmental screening' in assessment_name %}
                                            <td>{{ score }}</td>
                                            <td>{{ "%.2f"|format(score / 30) }}</td>
                                        {% else %}
                                            <td>
                                                {% if 'ciss' in assessment_name %}
                                                    {{ score }} / {{ max_domain_scores.get(domain, 'N/A') }}
                                                {% else %}
                                                    {{ score }}
                                                {% endif %}
                                            </td>
                                        {% endif %}
                                        {% if 'cbcl' in assessment_name and cbcl_domain_interpretations %}
                                            <td>{{ cbcl_domain_interpretations.get(domain, '—') }}</td>
                                        {% endif %}
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    {% endif %}

                    {% if 'cbcl' in assessment_name and cbcl_composites %}
                        <h3 class="mt-4">CBCL Composite Scores</h3>
                        <table class="table table-bordered table-striped">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Composite</th>
                                    <th>Score</th>
                                    <th>Interpretation</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>Internalizing</td>
                                    <td>{{ cbcl_composites.internalizing }}</td>
                                    <td>{{ cbcl_interpretations.internalizing }}</td>
                                </tr>
                                <tr>
                                    <td>Externalizing</td>
                                    <td>{{ cbcl_composites.externalizing }}</td>
                                    <td>{{ cbcl_interpretations.externalizing }}</td>
                                </tr>
                                <tr>
                                    <td>Total Other Problems</td>
                                    <td>{{ cbcl_composites.total_other_problems }}</td>
                                    <td>{{ cbcl_interpretations.total_other_problems or '—' }}</td>
                                </tr>
                                <tr>
                                    <td>Total Score</td>
                                    <td>{{ cbcl_composites.total_score }}</td>
                                    <td>{{ cbcl_interpretations.total_score }}</td>
                                </tr>
                            </tbody>
                        </table>
                    {% endif %}

                    {# Answered Questions for VADRS, GAD 7, CARS, HAM A or LEVEL 2 Anxiety Adult #}
                    {% if 'vadrs' in assessment_name or 'gad 7' in assessment_name or 'cars' in assessment_name or 'level 2 anxiety adult' in assessment_name or 'ham a' in assessment_name %}
                        <h3 class="mt-4">Answered Questions</h3>
                        <table class="table table-bordered table-striped">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Question</th>
                                    <th>Answer</th>
                                    <th>Score</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for response in assignment.responses %}
                                    <tr>
                                        <td>{{ response.question.text }}</td>
                                        <td>{{ response.choice.text }}</td>
                                        <td>{{ response.choice.weightage }}</td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    {% endif %}

                    {# Summary Section #}
                    {% if (taker_age_in_days is not none or taker_age_in_months is not none) and ('vsms' in assessment_name or 'social maturity' in assessment_name or 'dst' in assessment_name or 'ddst' in assessment_name or 'dsst' in assessment_name or 'developmental screening' in assessment_name or 'developmental screening' in assessment.name.lower()) %}
                        <div class="mt-4 p-3 border rounded">
                            {% if 'vsms' in assessment_name or 'social maturity' in assessment_name %}
                                <h4 class="mb-3">Social Maturity Summary</h4>
                                {% set sa_in_months = (domain_scores.values()|sum / 30) / domain_scores|length %}
                                {% set ca_in_months = taker_age_in_months %}
                                {% set social_quotient = (sa_in_months / ca_in_months) * 100 %}
                                <p><strong>Chronological Age (CA):</strong> {{ ca_in_months }} months</p>
                                <p><strong>Social Age (SA):</strong> {{ "%.2f"|format(sa_in_months) }} months</p>
                                <hr>
                                <p class="lead"><strong>Social Quotient (SQ):</strong> <span class="badge badge-primary" style="font-size: 1.1rem;">{{ "%.2f"|format(social_quotient) }}</span></p>
                            {% elif 'dst' in assessment_name or 'ddst' in assessment_name or 'dsst' in assessment_name or 'developmental screening' in assessment_name or 'developmental screening' in assessment.name.lower() %}
                                <h4 class="mb-3">Developmental Summary</h4>
                                <p><strong>Chronological Age (CA):</strong> {{ taker_age_in_months }} months</p>
                                <p><strong>Developmental Age (DA):</strong> {{ "%.2f"|format(total_raw_score / 30) }} months</p>
                                <hr>
                                <p class="lead"><strong>Developmental Quotient (DQ):</strong> <span class="badge badge-primary" style="font-size: 1.1rem;">{{ "%.2f"|format(dst_dq or 0) }}</span></p>

                                {% if 'ddst' not in assessment_name %}
                                <div class="mt-3">
                                    <h5>DST Interpretation Guide</h5>
                                    <table class="table table-bordered table-sm">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>DQ Range</th>
                                                <th>Classification</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq >= 130 }}"><td>&gt; 130</td><td>Very Superior</td></tr>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq >= 120 and dst_dq < 130 }}"><td>120 - 129</td><td>Superior</td></tr>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq >= 110 and dst_dq < 120 }}"><td>110 - 119</td><td>High Average</td></tr>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq >= 90 and dst_dq < 110 }}"><td>90 - 109</td><td>Average</td></tr>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq >= 80 and dst_dq < 90 }}"><td>80 - 89</td><td>Low Average</td></tr>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq >= 70 and dst_dq < 80 }}"><td>70 - 79</td><td>Borderline</td></tr>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq >= 50 and dst_dq < 70 }}"><td>50 - 69</td><td>Mild Development Delay</td></tr>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq >= 35 and dst_dq < 50 }}"><td>35 - 49</td><td>Moderate Development Delay</td></tr>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq >= 20 and dst_dq < 35 }}"><td>20 - 34</td><td>Severe Development Delay</td></tr>
                                            <tr class="{{ 'table-primary font-weight-bold' if dst_dq and dst_dq < 20 }}"><td>&lt; 20</td><td>Profound Development Delay</td></tr>
                                        </tbody>
                                    </table>
                                </div>
                                {% endif %}
                            {% else %}
                                <h4 class="mb-3">Developmental Summary</h4>
                                {% set da_in_months = (domain_scores.values()|sum / 30) / domain_scores|length %}
                                {% set ca_in_months = taker_age_in_months %}
                                {% set developmental_quotient = (da_in_months / ca_in_months) * 100 %}
                                <p><strong>Chronological Age (CA):</strong> {{ ca_in_months }} months</p>
                                <p><strong>Developmental Age (DA):</strong> {{ "%.2f"|format(da_in_months) }} months</p>
                                <hr>
                                <p class="lead"><strong>Developmental Quotient (DQ):</strong> <span class="badge badge-primary" style="font-size: 1.1rem;">{{ "%.2f"|format(developmental_quotient) }}</span></p>
                            {% endif %}
                        </div>
                    {% endif %}

                    {# Therapist Notes Section #}
                    {% if assignment.therapist_notes %}
                        <h3 class="mt-4">Therapist Notes</h3>
                        <div class="alert alert-secondary">
                            {{ assignment.therapist_notes }}
                        </div>
                    {% endif %}

                    {# Chart Section #}
                    {% if domain_scores and assessment_name != 'dst' %}
                        <div class="mt-4 chart-container">
                            <h4>Domain Performance Graph</h4>
                            <canvas id="domainChart" style="border: 1px solid #ccc;"></canvas>
                        </div>
                    {% endif %}
                {% else %}
                    <div class="alert alert-info mt-4">
                        <h4 class="alert-heading">Results Pending Review</h4>
                        <p>Thank you for completing the assessment. The results will be reviewed by a consultant, who will get in touch with you shortly. further queries email to connect @manaslr.com</p>
                    </div>
                {% endif %}

                <a href="{{ url_for('main.index') }}" class="btn btn-primary mt-3 no-print">Return to Home</a>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
{% if (current_user.is_authenticated and current_user.role in ['admin', 'consultant']) or is_free %}
    {% if domain_scores and assessment_name != 'dst' %}
        {% set assessment_name = assessment.name | lower | trim %}
        <script id="domain-chart-data" type="application/json">
            {{ {
                "labels": domain_scores.keys() | list,
                "values": domain_scores.values() | list,
                "useEquivalentAge": 'vsms' in assessment_name or 'social maturity' in assessment_name or 'ddst' in assessment_name or 'dsst' in assessment_name,
                "isCiss": 'ciss' in assessment_name
            } | tojson }}
        </script>
    {% endif %}
{% endif %}
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const dataEl = document.getElementById('domain-chart-data');
        if (!dataEl) return;
        const data = JSON.parse(dataEl.textContent || '{}');
        const ctx = document.getElementById('domainChart')?.getContext('2d');
        if (!ctx) return;
        Chart.register(ChartDataLabels);
        const labels = data.labels || [];
        const rawValues = data.values || [];
        const useEquivalentAge = !!data.useEquivalentAge;
        const isCiss = !!data.isCiss;

        const values = useEquivalentAge ? rawValues.map(d => +(d / 30).toFixed(2)) : rawValues;
        const yLabel = useEquivalentAge ? 'Equivalent Age (Months)' : 'Score';

        const formatter = (value) => useEquivalentAge ? value.toFixed(2) : value;

        const bg = 'rgba(54, 162, 235, 0.6)';
        const border = 'rgba(54, 162, 235, 1)';

        const chartOptions = {
            scales: {
                y: {
                    beginAtZero: true,
                    title: { display: true, text: yLabel }
                },
                x: {
                    title: { display: true, text: 'Domains' },
                    ticks: {
                        callback: function(value, index, values) {
                            const label = this.getLabelForValue(value);
                            if (label.length > 15) {
                                return label.split(' ');
                            }
                            return label;
                        },
                        autoSkip: false
                    }
                }
            },
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                datalabels: {
                    anchor: 'end',
                    align: 'top',
                    formatter: formatter,
                    font: { weight: 'bold' }
                }
            },
            animation: {
                onComplete: function() {
                    // Capture the chart image as Base64 when animation completes
                    const chartImage = document.getElementById('domainChart').toDataURL('image/png');
                    const input = document.getElementById('chart-image-input');
                    if (input) {
                        input.value = chartImage;
                    }
                }
            }
        };

        if (isCiss) {
            chartOptions.scales.y.max = 80;
            chartOptions.scales.y.ticks = {
                stepSize: 10
            };
        }

        const chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: yLabel,
                    data: values,
                    backgroundColor: bg,
                    borderColor: border,
                    borderWidth: 2,
                    fill: false
                }]
            },
            options: chartOptions
        });
    });
</script>
{% endblock %}