@extends('layouts.admin')

@section('title', 'Dashboard')

@section('content')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>

<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 32px;">
    <div>
        <h1 class="serif" style="font-size: 28px; margin: 0; font-weight: 600; color: #0f172a;">Store Overview & Analytics</h1>
        <p style="color: var(--text-muted); margin-top: 4px; font-size: 14px;">Monitor revenue, order volume, category performance, and active inventory in real-time.</p>
    </div>
    <div style="display: flex; gap: 12px;">
        <a href="{{ route('admin.products.create') }}" class="btn-admin btn-primary">
            <i data-lucide="plus" style="width: 18px;"></i>
            <span>Add New Product</span>
        </a>
    </div>
</div>

<!-- KPI Metric Grid -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 32px;">
    <div class="admin-card" style="display: flex; align-items: center; gap: 16px;">
        <div style="width: 50px; height: 50px; border-radius: 12px; background: #e0eff9; color: #186297; display: flex; align-items: center; justify-content: center;">
            <i data-lucide="indian-rupee" style="width: 24px;"></i>
        </div>
        <div>
            <div style="font-size: 13px; color: var(--text-muted); font-weight: 500;">Total Revenue</div>
            <div style="font-size: 24px; font-weight: 700; color: #0f172a; margin-top: 2px;">₹{{ number_format($totalRevenue, 2) }}</div>
        </div>
    </div>

    <div class="admin-card" style="display: flex; align-items: center; gap: 16px;">
        <div style="width: 50px; height: 50px; border-radius: 12px; background: #dbeafe; color: #1d4ed8; display: flex; align-items: center; justify-content: center;">
            <i data-lucide="shopping-cart" style="width: 24px;"></i>
        </div>
        <div>
            <div style="font-size: 13px; color: var(--text-muted); font-weight: 500;">Total Orders</div>
            <div style="font-size: 24px; font-weight: 700; color: #0f172a; margin-top: 2px;">{{ $totalOrders }}</div>
        </div>
    </div>

    <div class="admin-card" style="display: flex; align-items: center; gap: 16px;">
        <div style="width: 50px; height: 50px; border-radius: 12px; background: #fef3c7; color: #b45309; display: flex; align-items: center; justify-content: center;">
            <i data-lucide="clock" style="width: 24px;"></i>
        </div>
        <div>
            <div style="font-size: 13px; color: var(--text-muted); font-weight: 500;">Pending Orders</div>
            <div style="font-size: 24px; font-weight: 700; color: #0f172a; margin-top: 2px;">{{ $pendingOrders }}</div>
        </div>
    </div>

    <div class="admin-card" style="display: flex; align-items: center; gap: 16px;">
        <div style="width: 50px; height: 50px; border-radius: 12px; background: #f3e8ff; color: #7e22ce; display: flex; align-items: center; justify-content: center;">
            <i data-lucide="package" style="width: 24px;"></i>
        </div>
        <div>
            <div style="font-size: 13px; color: var(--text-muted); font-weight: 500;">Active Products</div>
            <div style="font-size: 24px; font-weight: 700; color: #0f172a; margin-top: 2px;">{{ $totalProducts }}</div>
        </div>
    </div>
</div>

<!-- Advanced Interactive Charts Section -->
<div style="display: grid; grid-template-columns: 2fr 1.2fr; gap: 24px; margin-bottom: 32px;">
    
    <!-- Chart 1: Monthly Sales & Order Volume Growth Trend -->
    <div class="admin-card">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
            <div>
                <h2 class="serif" style="font-size: 18px; margin: 0; color: #0f172a;">Sales & Revenue Growth Trend</h2>
                <p style="font-size: 12px; color: var(--text-muted); margin-top: 2px;">Monthly revenue performance (₹) and order volume over the last 6 months.</p>
            </div>
            <span style="background: #e0eff9; color: #186297; font-weight: 700; font-size: 11px; padding: 4px 10px; border-radius: 20px;">Monthly Analytics</span>
        </div>
        <div style="height: 290px; position: relative;">
            <canvas id="revenueChart"></canvas>
        </div>
    </div>

    <!-- Chart 2: Order Status Distribution with Value Labels -->
    <div class="admin-card">
        <div style="margin-bottom: 16px;">
            <h2 class="serif" style="font-size: 18px; margin: 0; color: #0f172a;">Order Status Breakdown</h2>
            <p style="font-size: 12px; color: var(--text-muted); margin-top: 2px;">Fulfillment distribution & order counts.</p>
        </div>
        <div style="height: 250px; position: relative; display: flex; align-items: center; justify-content: center;">
            <canvas id="statusChart"></canvas>
            <div style="position: absolute; text-align: center; pointer-events: none; margin-top: -30px;">
                <div style="font-size: 24px; font-weight: 800; color: #0f172a; line-height: 1;">{{ array_sum($statusCounts) }}</div>
                <div style="font-size: 10px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; margin-top: 2px;">Total Orders</div>
            </div>
        </div>
    </div>

</div>

<!-- Second Analytics Row: Category Revenue Distribution Bar Chart -->
<div class="admin-card" style="margin-bottom: 32px;">
    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
        <div>
            <h2 class="serif" style="font-size: 18px; margin: 0; color: #0f172a;">Category Sales & Revenue Distribution</h2>
            <p style="font-size: 12px; color: var(--text-muted); margin-top: 2px;">Earnings breakdown across product categories (Moisturisers, Cleansers, Serums, Sunscreens, Oils).</p>
        </div>
        <a href="{{ route('admin.categories.index') }}" style="color: #186297; font-size: 12px; font-weight: 600; text-decoration: none;">View Categories →</a>
    </div>
    <div style="height: 240px; position: relative;">
        <canvas id="categoryChart"></canvas>
    </div>
</div>

<!-- Main Table & Sidebar Grid -->
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 24px;">
    <!-- Recent Orders Table -->
    <div class="admin-card">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px;">
            <h2 class="serif" style="font-size: 18px; margin: 0; color: #0f172a;">Recent Customer Orders</h2>
            <a href="{{ route('admin.orders.index') }}" style="color: var(--primary); font-size: 13px; font-weight: 600; text-decoration: none;">View All Orders →</a>
        </div>

        @if($recentOrders->isEmpty())
            <div style="padding: 40px; text-align: center; color: var(--text-muted);">
                No orders recorded yet.
            </div>
        @else
            <div style="overflow-x: auto;">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>Order #</th>
                            <th>Customer</th>
                            <th>Items</th>
                            <th>Total</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($recentOrders as $order)
                            <tr>
                                <td>
                                    <strong style="color: var(--primary);">{{ $order->order_number }}</strong>
                                    <div style="font-size: 11px; color: var(--text-muted);">{{ $order->created_at->format('M d, H:i') }}</div>
                                </td>
                                <td>
                                    <div style="font-weight: 600; color: #0f172a;">{{ $order->customer_name }}</div>
                                    <div style="font-size: 12px; color: var(--text-muted);">{{ $order->customer_phone }}</div>
                                </td>
                                <td>{{ $order->items->sum('quantity') }} items</td>
                                <td><strong>₹{{ number_format($order->total_amount, 2) }}</strong></td>
                                <td>
                                    <span class="badge badge-{{ $order->order_status }}">{{ ucfirst($order->order_status) }}</span>
                                </td>
                                <td>
                                    <a href="{{ route('admin.orders.show', $order) }}" class="btn-admin btn-secondary" style="padding: 6px 12px; font-size: 12px;">
                                        <i data-lucide="eye" style="width: 14px;"></i> View
                                    </a>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif
    </div>

    <!-- Low Stock & Quick Actions Sidebar -->
    <div style="display: flex; flex-direction: column; gap: 24px;">
        <div class="admin-card">
            <h2 class="serif" style="font-size: 18px; margin: 0 0 16px 0; color: #0f172a;">Low Stock Warning</h2>
            @if($lowStockProducts->isEmpty())
                <p style="color: var(--text-muted); font-size: 13px;">All products have healthy inventory levels!</p>
            @else
                <div style="display: flex; flex-direction: column; gap: 12px;">
                    @foreach($lowStockProducts as $prod)
                        <div style="display: flex; align-items: center; justify-content: space-between; padding: 10px 12px; background: #f8faf9; border: 1px solid var(--border-color); border-radius: 10px;">
                            <div>
                                <div style="font-weight: 600; font-size: 13px; color: #0f172a;">{{ $prod->name }}</div>
                                <div style="font-size: 11px; color: var(--text-muted);">Category: {{ $prod->category->name ?? 'Unassigned' }}</div>
                            </div>
                            <span class="badge badge-pending">{{ $prod->stock }} left</span>
                        </div>
                    @endforeach
                </div>
            @endif
        </div>

        <div class="admin-card">
            <h2 class="serif" style="font-size: 18px; margin: 0 0 16px 0; color: #0f172a;">Quick Management</h2>
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <a href="{{ route('admin.categories.index') }}" class="btn-admin btn-secondary" style="justify-content: flex-start;">
                    <i data-lucide="layers" style="width: 16px;"></i> Manage Categories ({{ $categoriesCount }})
                </a>
                <a href="{{ route('admin.coupons.index') }}" class="btn-admin btn-secondary" style="justify-content: flex-start;">
                    <i data-lucide="ticket" style="width: 16px;"></i> Manage Discounts & Coupons
                </a>
                <a href="{{ route('admin.customers.index') }}" class="btn-admin btn-secondary" style="justify-content: flex-start;">
                    <i data-lucide="users" style="width: 16px;"></i> Customer Directory ({{ $totalCustomers }})
                </a>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    Chart.register(ChartDataLabels);

    const rawStatusCounts = {!! json_encode($statusCounts) !!};

    // 1. Sales & Revenue Trend Chart (Area Line Chart)
    const ctxRevenue = document.getElementById('revenueChart').getContext('2d');
    const gradientRevenue = ctxRevenue.createLinearGradient(0, 0, 0, 250);
    gradientRevenue.addColorStop(0, 'rgba(24, 98, 151, 0.4)');
    gradientRevenue.addColorStop(1, 'rgba(24, 98, 151, 0.01)');

    new Chart(ctxRevenue, {
        type: 'line',
        data: {
            labels: {!! json_encode($months) !!},
            datasets: [
                {
                    label: 'Gross Revenue (₹)',
                    data: {!! json_encode($revenueData) !!},
                    borderColor: '#186297',
                    borderWidth: 3,
                    backgroundColor: gradientRevenue,
                    fill: true,
                    tension: 0.35,
                    pointBackgroundColor: '#186297',
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    yAxisID: 'y'
                },
                {
                    label: 'Total Orders',
                    data: {!! json_encode($ordersCountData) !!},
                    borderColor: '#0284c7',
                    borderWidth: 2,
                    borderDash: [4, 4],
                    pointBackgroundColor: '#0284c7',
                    pointRadius: 3,
                    fill: false,
                    tension: 0.35,
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false,
            },
            plugins: {
                datalabels: { display: false },
                legend: {
                    position: 'top',
                    labels: { font: { family: 'Plus Jakarta Sans', size: 12 }, usePointStyle: true }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            if (context.dataset.label.includes('Revenue')) {
                                return 'Revenue: ₹' + context.parsed.y.toLocaleString('en-IN');
                            }
                            return 'Orders: ' + context.parsed.y;
                        }
                    }
                }
            },
            scales: {
                x: { grid: { display: false } },
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    ticks: { callback: function(val) { return '₹' + (val / 1000) + 'k'; } },
                    grid: { color: '#f1f5f9' }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    grid: { drawOnChartArea: false },
                    ticks: { precision: 0 }
                }
            }
        }
    });

    // 2. Order Status Doughnut Chart WITH EXPLICIT VALUE LABELS & LEGEND VALUES
    const ctxStatus = document.getElementById('statusChart').getContext('2d');
    
    // Build legend labels with numerical values e.g. "Delivered (18)"
    const statusKeys = Object.keys(rawStatusCounts);
    const statusValues = Object.values(rawStatusCounts);
    const legendLabelsWithValues = statusKeys.map((key, idx) => key + ' (' + statusValues[idx] + ')');

    new Chart(ctxStatus, {
        type: 'doughnut',
        data: {
            labels: legendLabelsWithValues,
            datasets: [{
                data: statusValues,
                backgroundColor: [
                    '#15803d', // Delivered - Green
                    '#186297', // Shipped - Brand Blue
                    '#0284c7', // Processing - Light Blue
                    '#b45309', // Pending - Amber
                    '#b91c1c'  // Cancelled - Red
                ],
                borderWidth: 2,
                borderColor: '#ffffff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                datalabels: {
                    color: '#ffffff',
                    font: { weight: 'bold', size: 12, family: 'Plus Jakarta Sans' },
                    formatter: function(value) {
                        return value > 0 ? value : '';
                    }
                },
                legend: {
                    position: 'bottom',
                    labels: {
                        font: { family: 'Plus Jakarta Sans', size: 11, weight: '600' },
                        usePointStyle: true,
                        padding: 12
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return ' ' + context.label + ': ' + context.parsed + ' orders';
                        }
                    }
                }
            },
            cutout: '66%'
        }
    });

    // 3. Category Sales Bar Chart WITH TOP VALUE LABELS
    const ctxCategory = document.getElementById('categoryChart').getContext('2d');
    new Chart(ctxCategory, {
        type: 'bar',
        data: {
            labels: {!! json_encode($categoryLabels) !!},
            datasets: [{
                label: 'Sales Earnings (₹)',
                data: {!! json_encode($categoryData) !!},
                backgroundColor: '#186297',
                borderRadius: 8,
                barThickness: 28
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                datalabels: {
                    anchor: 'end',
                    align: 'top',
                    color: '#0f172a',
                    font: { weight: 'bold', size: 11, family: 'Plus Jakarta Sans' },
                    formatter: function(value) {
                        return '₹' + Math.round(value).toLocaleString('en-IN');
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return 'Earnings: ₹' + context.parsed.y.toLocaleString('en-IN');
                        }
                    }
                }
            },
            scales: {
                x: { grid: { display: false } },
                y: {
                    ticks: { callback: function(val) { return '₹' + (val / 1000) + 'k'; } },
                    grid: { color: '#f1f5f9' }
                }
            }
        }
    });

});
</script>
@endsection
