{% extends "base.html" %}

{% block title %}OpenFinOps - Overview Dashboard{% endblock %}

{% block extra_head %}
<style>
    /* Metric Cards */
    .metric-card {
        position: relative;
        overflow: hidden;
    }

    .metric-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
        transition: left 0.5s;
    }

    .metric-card:hover::before {
        left: 100%;
    }

    /* Chart Containers */
    .chart-container {
        position: relative;
        height: 300px;
        margin: 20px 0;
    }

    .chart-container-tall {
        height: 400px;
    }

    /* Stat Badge */
    .stat-badge {
        display: inline-flex;
        align-items: center;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 0.875rem;
        font-weight: 600;
    }

    .stat-up {
        background: rgba(50, 205, 50, 0.2);
        color: #32cd32;
    }

    .stat-down {
        background: rgba(255, 107, 107, 0.2);
        color: #ff6b6b;
    }
</style>
{% endblock %}

{% block content %}
<!-- Hero Section -->
<div class="mb-8">
    <h2 class="text-4xl font-bold bg-gradient-to-r from-cyan-400 to-blue-500 bg-clip-text text-transparent">
        FinOps Intelligence Dashboard
    </h2>
    <p class="text-gray-400 mt-2">Real-time AI/ML cost observability and optimization</p>
</div>

<!-- Key Metrics Cards -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
    <!-- Total Cost Card -->
    <div class="glass metric-card rounded-xl p-6 card-hover">
        <div class="flex items-center justify-between mb-4">
            <div class="p-3 rounded-lg gradient-primary">
                <i class="fas fa-dollar-sign text-2xl text-white"></i>
            </div>
            <span class="stat-badge stat-down" id="total-cost-trend">
                <i class="fas fa-arrow-down mr-1"></i>5.2%
            </span>
        </div>
        <h3 class="text-gray-400 text-sm font-medium">Total Cost</h3>
        <p class="text-3xl font-bold mt-2" id="total-cost">$0</p>
        <p class="text-gray-500 text-sm mt-2">Last 30 days</p>
    </div>

    <!-- AI/ML Cost Card -->
    <div class="glass metric-card rounded-xl p-6 card-hover">
        <div class="flex items-center justify-between mb-4">
            <div class="p-3 rounded-lg gradient-info">
                <i class="fas fa-brain text-2xl text-white"></i>
            </div>
            <span class="stat-badge stat-up" id="ai-cost-trend">
                <i class="fas fa-arrow-up mr-1"></i>12.3%
            </span>
        </div>
        <h3 class="text-gray-400 text-sm font-medium">AI/ML Cost</h3>
        <p class="text-3xl font-bold mt-2" id="ai-ml-cost">$0</p>
        <p class="text-gray-500 text-sm mt-2">Training & Inference</p>
    </div>

    <!-- Cloud Cost Card -->
    <div class="glass metric-card rounded-xl p-6 card-hover">
        <div class="flex items-center justify-between mb-4">
            <div class="p-3 rounded-lg gradient-success">
                <i class="fas fa-cloud text-2xl text-white"></i>
            </div>
            <span class="stat-badge stat-down" id="cloud-cost-trend">
                <i class="fas fa-arrow-down mr-1"></i>3.1%
            </span>
        </div>
        <h3 class="text-gray-400 text-sm font-medium">Cloud Infrastructure</h3>
        <p class="text-3xl font-bold mt-2" id="cloud-cost">$0</p>
        <p class="text-gray-500 text-sm mt-2">Multi-cloud spend</p>
    </div>

    <!-- Optimization Savings Card -->
    <div class="glass metric-card rounded-xl p-6 card-hover">
        <div class="flex items-center justify-between mb-4">
            <div class="p-3 rounded-lg gradient-warning">
                <i class="fas fa-chart-line text-2xl text-white"></i>
            </div>
            <span class="stat-badge stat-up" id="savings-trend">
                <i class="fas fa-arrow-up mr-1"></i>18.5%
            </span>
        </div>
        <h3 class="text-gray-400 text-sm font-medium">Potential Savings</h3>
        <p class="text-3xl font-bold mt-2" id="potential-savings">$0</p>
        <p class="text-gray-500 text-sm mt-2">AI recommendations</p>
    </div>
</div>

<!-- Charts Row 1 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
    <!-- Cost Trend Chart -->
    <div class="glass rounded-xl p-6">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-xl font-semibold">
                <i class="fas fa-chart-area mr-2 text-cyan-400"></i>Cost Trend (7 Days)
            </h3>
            <div class="flex space-x-2">
                <button class="px-3 py-1 rounded-lg glass-strong text-sm hover:bg-white/10 transition">7D</button>
                <button class="px-3 py-1 rounded-lg text-sm hover:bg-white/10 transition">30D</button>
                <button class="px-3 py-1 rounded-lg text-sm hover:bg-white/10 transition">90D</button>
            </div>
        </div>
        <div class="chart-container">
            <canvas id="costTrendChart"></canvas>
        </div>
    </div>

    <!-- Service Breakdown Chart -->
    <div class="glass rounded-xl p-6">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-xl font-semibold">
                <i class="fas fa-chart-pie mr-2 text-blue-400"></i>Cost by Service
            </h3>
            <span class="text-sm text-gray-400">Current Month</span>
        </div>
        <div class="chart-container">
            <canvas id="serviceBreakdownChart"></canvas>
        </div>
    </div>
</div>

<!-- Charts Row 2 -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
    <!-- Top Resources -->
    <div class="glass rounded-xl p-6 lg:col-span-2">
        <h3 class="text-xl font-semibold mb-4">
            <i class="fas fa-server mr-2 text-purple-400"></i>Top Resources by Cost
        </h3>
        <div class="chart-container">
            <canvas id="topResourcesChart"></canvas>
        </div>
    </div>

    <!-- Live Activity Feed -->
    <div class="glass rounded-xl p-6">
        <h3 class="text-xl font-semibold mb-4">
            <i class="fas fa-rss mr-2 text-green-400"></i>Live Activity
        </h3>
        <div class="space-y-3 overflow-y-auto" style="max-height: 300px;" id="activity-feed">
            <div class="p-3 rounded-lg glass-strong">
                <p class="text-sm font-medium">New ML Training Job</p>
                <p class="text-xs text-gray-400 mt-1">SageMaker • $234.50/hr</p>
                <p class="text-xs text-gray-500 mt-1">Just now</p>
            </div>
            <div class="p-3 rounded-lg glass-strong">
                <p class="text-sm font-medium">EC2 Instance Scaled</p>
                <p class="text-xs text-gray-400 mt-1">us-east-1 • +15 instances</p>
                <p class="text-xs text-gray-500 mt-1">2 min ago</p>
            </div>
            <div class="p-3 rounded-lg glass-strong">
                <p class="text-sm font-medium">Cost Alert Triggered</p>
                <p class="text-xs text-gray-400 mt-1">Lambda • Budget exceeded</p>
                <p class="text-xs text-gray-500 mt-1">5 min ago</p>
            </div>
        </div>
    </div>
</div>

<!-- AI Recommendations -->
<div class="glass rounded-xl p-6">
    <h3 class="text-xl font-semibold mb-4">
        <i class="fas fa-lightbulb mr-2 text-yellow-400"></i>AI-Powered Recommendations
    </h3>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="p-4 rounded-lg glass-strong border-l-4 border-cyan-400">
            <div class="flex items-start justify-between">
                <div>
                    <h4 class="font-semibold mb-2">Right-size EC2 Instances</h4>
                    <p class="text-sm text-gray-400">12 instances are over-provisioned</p>
                    <p class="text-2xl font-bold mt-3 text-cyan-400">Save $8,340/mo</p>
                </div>
                <button class="px-4 py-2 rounded-lg gradient-primary text-sm font-medium hover:opacity-90 transition">
                    Apply
                </button>
            </div>
        </div>
        <div class="p-4 rounded-lg glass-strong border-l-4 border-green-400">
            <div class="flex items-start justify-between">
                <div>
                    <h4 class="font-semibold mb-2">Enable S3 Lifecycle Rules</h4>
                    <p class="text-sm text-gray-400">Move old data to cheaper storage</p>
                    <p class="text-2xl font-bold mt-3 text-green-400">Save $3,200/mo</p>
                </div>
                <button class="px-4 py-2 rounded-lg gradient-success text-sm font-medium hover:opacity-90 transition">
                    Apply
                </button>
            </div>
        </div>
        <div class="p-4 rounded-lg glass-strong border-l-4 border-purple-400">
            <div class="flex items-start justify-between">
                <div>
                    <h4 class="font-semibold mb-2">Optimize Lambda Memory</h4>
                    <p class="text-sm text-gray-400">8 functions using excess memory</p>
                    <p class="text-2xl font-bold mt-3 text-purple-400">Save $1,850/mo</p>
                </div>
                <button class="px-4 py-2 rounded-lg gradient-info text-sm font-medium hover:opacity-90 transition">
                    Apply
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
    // Chart configurations
    const chartDefaults = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                labels: {
                    color: '#9ca3af',
                    font: { family: 'Inter' }
                }
            }
        },
        scales: {
            x: {
                grid: { color: 'rgba(255, 255, 255, 0.1)' },
                ticks: { color: '#9ca3af' }
            },
            y: {
                grid: { color: 'rgba(255, 255, 255, 0.1)' },
                ticks: { color: '#9ca3af' }
            }
        }
    };

    // Cost Trend Chart
    const costTrendCtx = document.getElementById('costTrendChart').getContext('2d');
    const costTrendChart = new Chart(costTrendCtx, {
        type: 'line',
        data: {
            labels: ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5', 'Day 6', 'Day 7'],
            datasets: [{
                label: 'Total Cost ($)',
                data: [45000, 52000, 48000, 61000, 55000, 58000, 52000],
                borderColor: '#00d4aa',
                backgroundColor: 'rgba(0, 212, 170, 0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: chartDefaults
    });

    // Service Breakdown Chart
    const serviceCtx = document.getElementById('serviceBreakdownChart').getContext('2d');
    const serviceChart = new Chart(serviceCtx, {
        type: 'doughnut',
        data: {
            labels: ['EC2', 'S3', 'SageMaker', 'Lambda', 'Other'],
            datasets: [{
                data: [25000, 12000, 35000, 6000, 8000],
                backgroundColor: [
                    '#00d4aa',
                    '#00a8ff',
                    '#3742fa',
                    '#a29bfe',
                    '#ffa500'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#9ca3af',
                        font: { family: 'Inter' },
                        padding: 15
                    }
                }
            }
        }
    });

    // Top Resources Chart
    const resourcesCtx = document.getElementById('topResourcesChart').getContext('2d');
    const resourcesChart = new Chart(resourcesCtx, {
        type: 'bar',
        data: {
            labels: ['ml-training-cluster', 'api-prod-ec2', 'data-lake-s3', 'inference-lambda', 'analytics-emr'],
            datasets: [{
                label: 'Cost ($)',
                data: [22000, 18000, 15000, 12000, 9000],
                backgroundColor: 'rgba(0, 212, 170, 0.6)',
                borderColor: '#00d4aa',
                borderWidth: 2
            }]
        },
        options: {
            ...chartDefaults,
            indexAxis: 'y'
        }
    });

    // WebSocket event handlers
    socket.on('dashboard_update', function(data) {
        // Update metric cards
        document.getElementById('total-cost').textContent =
            '$' + (data.total_cost || 0).toLocaleString('en-US', {maximumFractionDigits: 0});
        document.getElementById('ai-ml-cost').textContent =
            '$' + (data.ai_ml_cost || 0).toLocaleString('en-US', {maximumFractionDigits: 0});
        document.getElementById('cloud-cost').textContent =
            '$' + (data.cloud_cost || 0).toLocaleString('en-US', {maximumFractionDigits: 0});

        // Calculate potential savings (15% of total)
        const savings = Math.round(data.total_cost * 0.15);
        document.getElementById('potential-savings').textContent =
            '$' + savings.toLocaleString('en-US');

        // Update cost trend chart
        if (data.cost_trend && data.cost_trend.length > 0) {
            costTrendChart.data.labels = data.cost_trend.map(d => d.date);
            costTrendChart.data.datasets[0].data = data.cost_trend.map(d => d.cost);
            costTrendChart.update('none'); // Update without animation for smooth live updates
        }

        // Update service breakdown chart
        if (data.cost_by_service) {
            const services = Object.keys(data.cost_by_service);
            const costs = Object.values(data.cost_by_service);
            serviceChart.data.labels = services;
            serviceChart.data.datasets[0].data = costs;
            serviceChart.update('none');
        }

        // Update top resources chart
        if (data.top_resources && data.top_resources.length > 0) {
            resourcesChart.data.labels = data.top_resources.map(r => r.name);
            resourcesChart.data.datasets[0].data = data.top_resources.map(r => r.cost);
            resourcesChart.update('none');
        }

        console.log('📊 Dashboard updated with live data');
    });

    // Initial data fetch
    fetch('/api/metrics')
        .then(response => response.json())
        .then(data => {
            socket.emit('dashboard_update', data);
        });
</script>
{% endblock %}
