{% extends "base.html" %}
{% load static %}

{% block title %}Contract Detail - AI ML Operations{% endblock %}

{% block content %}
<div class="section">
    <div class="container">
        <div style="margin-bottom: 2rem;">
            <a href="{% url 'contracts' %}" class="btn" style="padding: 0.5rem 1.5rem; font-size: 0.9rem;">Back to
                Contracts</a>
        </div>

        {% if is_new %}
        <h1 class="section-title" style="text-align: left;">New Contract</h1>
        <div class="card" style="max-width: 600px;">
            <form method="post" action='{% url "new_contract" %}'>
                {% csrf_token %}
                {{ form.as_p }}
                <button type="submit" class="btn" style="margin-top: 1rem;">Create</button>
            </form>
        </div>

        {% else %}
        <h1 class="section-title" style="text-align: left;">{{ contract.name }}</h1>
        <div class="card" style="max-width: 600px;">
            <form method="post" action='{% url "contract_detail" contract.slug %}'>
                {% csrf_token %}
                {{ form.as_p }}
                <button type="submit" class="btn" style="margin-top: 1rem;">Update</button>
            </form>
        </div>
        {% endif %}

        <hr style="margin: 40px 0; border: 0; border-top: 1px solid rgba(255,255,255,0.1);">

        <!-- ═══════════════════════════════════════════════════════ -->
        <!--  EARNED VALUE MANAGEMENT SECTION                       -->
        <!-- ═══════════════════════════════════════════════════════ -->
        {% if evm %}
        <h2 class="section-title" style="text-align: left; font-size: 2rem;">Earned Value Management</h2>

        <!-- EVM KPI Cards -->
        <div
            style="display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 16px; margin-bottom: 2rem;">
            <!-- BAC -->
            <div class="card evm-kpi-card">
                <span class="evm-kpi-label">BAC (Budget)</span>
                <span class="evm-kpi-value">${{ evm.bac_dollars|floatformat:2 }}</span>
                <span class="evm-kpi-sub">{{ evm.bac_hours }} hrs</span>
            </div>
            <!-- PV -->
            <div class="card evm-kpi-card">
                <span class="evm-kpi-label">PV (Planned)</span>
                <span class="evm-kpi-value">${{ evm.pv_dollars|floatformat:2 }}</span>
                <span class="evm-kpi-sub">{{ evm.pv_hours }} hrs</span>
            </div>
            <!-- EV -->
            <div class="card evm-kpi-card">
                <span class="evm-kpi-label">EV (Earned)</span>
                <span class="evm-kpi-value" style="color: #39ff14;">${{ evm.ev_dollars|floatformat:2 }}</span>
                <span class="evm-kpi-sub">{{ evm.ev_hours }} hrs · {{ evm.percent_complete }}% done</span>
            </div>
            <!-- AC -->
            <div class="card evm-kpi-card">
                <span class="evm-kpi-label">AC (Actual Cost)</span>
                <span class="evm-kpi-value" style="color: #bc13fe;">${{ evm.ac_dollars|floatformat:2 }}</span>
                <span class="evm-kpi-sub">{{ evm.ac_hours }} hrs spent</span>
            </div>
        </div>

        <!-- Variance & Index Cards -->
        <div
            style="display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 16px; margin-bottom: 2rem;">
            <!-- SV -->
            <div class="card evm-kpi-card">
                <span class="evm-kpi-label">Schedule Variance</span>
                <span class="evm-kpi-value {% if evm.sv_dollars >= 0 %}evm-positive{% else %}evm-negative{% endif %}">
                    ${{ evm.sv_dollars|floatformat:2 }}
                </span>
                <span class="evm-kpi-sub">{% if evm.sv_dollars >= 0 %}Ahead{% else %}Behind{% endif %} schedule</span>
            </div>
            <!-- CV -->
            <div class="card evm-kpi-card">
                <span class="evm-kpi-label">Cost Variance</span>
                <span class="evm-kpi-value {% if evm.cv_dollars >= 0 %}evm-positive{% else %}evm-negative{% endif %}">
                    ${{ evm.cv_dollars|floatformat:2 }}
                </span>
                <span class="evm-kpi-sub">{% if evm.cv_dollars >= 0 %}Under{% else %}Over{% endif %} budget</span>
            </div>
            <!-- SPI -->
            <div class="card evm-kpi-card">
                <span class="evm-kpi-label">SPI</span>
                <span
                    class="evm-kpi-value {% if evm.spi >= 1 %}evm-positive{% elif evm.spi > 0 %}evm-negative{% endif %}">
                    {{ evm.spi }}
                </span>
                <span class="evm-kpi-sub">{% if evm.spi >= 1 %}On/ahead{% elif evm.spi > 0 %}Behind{% else %}No data{%
                    endif %}</span>
            </div>
            <!-- CPI -->
            <div class="card evm-kpi-card">
                <span class="evm-kpi-label">CPI</span>
                <span
                    class="evm-kpi-value {% if evm.cpi >= 1 %}evm-positive{% elif evm.cpi > 0 %}evm-negative{% endif %}">
                    {{ evm.cpi }}
                </span>
                <span class="evm-kpi-sub">{% if evm.cpi >= 1 %}Efficient{% elif evm.cpi > 0 %}Over-spending{% else %}No
                    data{% endif %}</span>
            </div>
        </div>

        <!-- Charts: full-width rows -->
        <div class="evm-charts-stack">
            <div class="card evm-chart-card">
                <h3 class="evm-chart-title">S-Curve (PV vs EV vs AC)</h3>
                <div class="evm-chart-canvas-wrap">
                    <canvas id="evmSCurveChart"></canvas>
                </div>
            </div>
            <div class="card evm-chart-card">
                <h3 class="evm-chart-title">Performance Indices</h3>
                <div class="evm-chart-canvas-wrap evm-chart-canvas-wrap--compact">
                    <canvas id="evmIndexChart"></canvas>
                </div>
            </div>
        </div>
        {% endif %}

        <hr style="margin: 40px 0; border: 0; border-top: 1px solid rgba(255,255,255,0.1);">

        <h2 class="section-title" style="text-align: left; font-size: 2rem;">Charge Numbers</h2>
        {% if charge_numbers %}
        {% if mermaid_gantt %}
        <div class="card charge-gantt-card" style="margin-bottom: 2rem; background: var(--surface-color);">
            <h3 class="evm-chart-title" style="margin-bottom: 1rem;">Timeline</h3>
            <div class="charge-gantt-scroll">
                <div class="mermaid">
                    {{ mermaid_gantt|safe }}
                </div>
            </div>
        </div>
        {% endif %}

        <div class="card" style="margin-bottom: 2rem;">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Slug/ID/Name</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>% Complete</th>
                            <th>Start Date</th>
                            <th>End Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for cn in charge_numbers %}
                        <tr>
                            <td>{{ cn }}</td>
                            <td>{{ cn.get_charge_number_type_display }}</td>
                            <td>${{ cn.amount|floatformat:2 }}</td>
                            <td>
                                <span class="badge"
                                    style="background: rgba(0, 243, 255, 0.1); border: 1px solid var(--primary-color); color: var(--primary-color);">
                                    {{ cn.percent_complete|floatformat:0 }}%
                                </span>
                            </td>
                            <td class="charge-date-cell">{{ cn.start_date|default:"-" }}</td>
                            <td class="charge-date-cell">{{ cn.end_date|default:"-" }}</td>
                            <td>
                                <a href="{% url 'update_charge_number' cn.slug %}" class="text-cyber-cyan"
                                    style="font-size: 0.9rem;">Edit</a>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card" style="max-width: 600px;">
            <h3 style="margin-bottom: 1rem;">Create a new charge number</h3>
            <form method="post" action='{% url "new_charge_number" contract.slug %}'>
                {% csrf_token %}
                {{ charge_number_form.as_p }}
                <button type="submit" class="btn" style="margin-top: 1rem;">Add Charge Number</button>
            </form>
        </div>
        {% else %}
        <div class="card" style="max-width: 600px;">
            <p style="color: var(--text-muted); margin-bottom: 1.5rem;">There are no charge numbers for this contract.
            </p>
            <form method="post" action='{% url "new_charge_number" contract.slug %}'>
                {% csrf_token %}
                {{ charge_number_form.as_p }}
                <button type="submit" class="btn" style="margin-top: 1rem;">Add Charge Number</button>
            </form>
        </div>
        {% endif %}

        {% endif %}
    </div>
</div>

<style>
    .evm-kpi-card {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px 16px;
        text-align: center;
        background: var(--surface-color);
        border: 1px solid rgba(255, 255, 255, 0.08);
        border-radius: 12px;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .evm-kpi-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 24px rgba(0, 243, 255, 0.08);
    }

    .evm-kpi-label {
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 1.5px;
        color: var(--text-muted, #888);
        margin-bottom: 6px;
        font-weight: 600;
    }

    .evm-kpi-value {
        font-size: 1.5rem;
        font-weight: 800;
        color: #fff;
        line-height: 1.2;
    }

    .evm-kpi-sub {
        font-size: 0.75rem;
        color: var(--text-muted, #888);
        margin-top: 4px;
    }

    .evm-positive {
        color: #39ff14 !important;
    }

    .evm-negative {
        color: #ff4444 !important;
    }

    .evm-charts-stack {
        display: flex;
        flex-direction: column;
        gap: 20px;
        margin-bottom: 2rem;
        width: 100%;
    }

    .evm-chart-card {
        padding: 20px;
        width: 100%;
    }

    .evm-chart-title {
        margin-bottom: 1rem;
        font-size: 1.1rem;
        color: var(--text-muted);
    }

    .evm-chart-canvas-wrap {
        position: relative;
        width: 100%;
        height: 320px;
    }

    .evm-chart-canvas-wrap--compact {
        height: 260px;
        max-width: 480px;
    }

    .charge-gantt-scroll {
        overflow-x: auto;
        width: 100%;
        padding-bottom: 0.5rem;
    }

    .charge-gantt-scroll .mermaid {
        min-width: 720px;
    }

    .charge-date-cell {
        white-space: nowrap;
    }
</style>

<script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true, theme: 'dark' });
</script>

{% if evm_chart_json %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const raw = '{{ evm_chart_json|escapejs }}';
        if (!raw) return;
        const data = JSON.parse(raw);

        Chart.defaults.color = '#e0e0e0';
        Chart.defaults.borderColor = 'rgba(255, 255, 255, 0.1)';

        /* ─────── S-Curve Chart ─────── */
        const sCurveCanvas = document.getElementById('evmSCurveChart');
        if (sCurveCanvas && data.time_series && data.time_series.length > 0) {
            const labels = data.time_series.map(d => d.month);
            const pvData = data.time_series.map(d => d.pv);
            const evData = data.time_series.map(d => d.ev);
            const acData = data.time_series.map(d => d.ac);

            new Chart(sCurveCanvas.getContext('2d'), {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: 'Planned Value (PV)',
                            data: pvData,
                            borderColor: '#00f3ff',
                            backgroundColor: 'rgba(0, 243, 255, 0.08)',
                            borderWidth: 2,
                            fill: true,
                            tension: 0.3,
                            pointRadius: 3,
                            pointBackgroundColor: '#00f3ff',
                        },
                        {
                            label: 'Earned Value (EV)',
                            data: evData,
                            borderColor: '#39ff14',
                            backgroundColor: 'rgba(57, 255, 20, 0.08)',
                            borderWidth: 2,
                            fill: true,
                            tension: 0.3,
                            pointRadius: 3,
                            pointBackgroundColor: '#39ff14',
                        },
                        {
                            label: 'Actual Cost (AC)',
                            data: acData,
                            borderColor: '#bc13fe',
                            backgroundColor: 'rgba(188, 19, 254, 0.08)',
                            borderWidth: 2,
                            fill: true,
                            tension: 0.3,
                            pointRadius: 3,
                            pointBackgroundColor: '#bc13fe',
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: { mode: 'index', intersect: false },
                    plugins: {
                        legend: { labels: { color: '#e0e0e0', usePointStyle: true, padding: 16 } },
                        tooltip: {
                            callbacks: {
                                label: ctx => `${ctx.dataset.label}: $${ctx.parsed.y.toLocaleString()}`
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: { color: 'rgba(255,255,255,0.05)' },
                            ticks: { color: '#a0a0a0' }
                        },
                        y: {
                            beginAtZero: true,
                            title: { display: true, text: 'Dollars ($)', color: '#a0a0a0' },
                            grid: { color: 'rgba(255,255,255,0.05)' },
                            ticks: {
                                color: '#a0a0a0',
                                callback: v => '$' + v.toLocaleString()
                            }
                        }
                    }
                }
            });
        }

        /* ─────── SPI / CPI Bar Chart ─────── */
        const indexCanvas = document.getElementById('evmIndexChart');
        if (indexCanvas) {
            const spi = data.spi || 0;
            const cpi = data.cpi || 0;

            new Chart(indexCanvas.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: ['SPI', 'CPI'],
                    datasets: [{
                        label: 'Performance Index',
                        data: [spi, cpi],
                        backgroundColor: [
                            spi >= 1 ? 'rgba(57, 255, 20, 0.6)' : 'rgba(255, 68, 68, 0.6)',
                            cpi >= 1 ? 'rgba(57, 255, 20, 0.6)' : 'rgba(255, 68, 68, 0.6)',
                        ],
                        borderColor: [
                            spi >= 1 ? '#39ff14' : '#ff4444',
                            cpi >= 1 ? '#39ff14' : '#ff4444',
                        ],
                        borderWidth: 2,
                        borderRadius: 6,
                        barPercentage: 0.5,
                    }]
                },
                plugins: [{
                    id: 'baselineLine',
                    afterDraw(chart) {
                        const yScale = chart.scales.y;
                        const ctx = chart.ctx;
                        const yPixel = yScale.getPixelForValue(1);
                        ctx.save();
                        ctx.strokeStyle = '#00f3ff';
                        ctx.lineWidth = 2;
                        ctx.setLineDash([6, 4]);
                        ctx.beginPath();
                        ctx.moveTo(chart.chartArea.left, yPixel);
                        ctx.lineTo(chart.chartArea.right, yPixel);
                        ctx.stroke();
                        // Label
                        ctx.fillStyle = '#00f3ff';
                        ctx.font = '11px Inter, sans-serif';
                        ctx.fillText('Target = 1.0', chart.chartArea.right - 72, yPixel - 6);
                        ctx.restore();
                    }
                }],
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            callbacks: {
                                label: ctx => `${ctx.label}: ${ctx.parsed.y.toFixed(2)}`
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: { display: false },
                            ticks: { color: '#e0e0e0', font: { size: 14, weight: 'bold' } }
                        },
                        y: {
                            beginAtZero: true,
                            suggestedMax: Math.max(spi, cpi, 1.5) + 0.3,
                            grid: { color: 'rgba(255,255,255,0.05)' },
                            ticks: { color: '#a0a0a0' }
                        }
                    }
                }
            });
        }
    });
</script>
{% endif %}
{% endblock %}