@extends('layouts.admin')

@section('page_title', 'Admin Dashboard - ' . $branding['company_name'])

@section('content')

{{-- Welcome & date --}}
<div class="dashboard-welcome mb-3 mb-md-4">
    <div class="d-flex flex-wrap justify-content-between align-items-start gap-2 gap-md-3">
        <div class="min-w-0">
            <p class="text-muted small mb-1 fw-semibold text-uppercase d-none d-sm-block">{{ now()->format('l, F j, Y') }}</p>
            <p class="text-muted mb-1 fw-semibold text-uppercase d-sm-none" style="font-size:0.65rem;">{{ now()->format('M j, Y') }}</p>
            <h4 class="fw-bold text-secondary mb-1 dashboard-welcome-title">Welcome, {{ Auth::user()->name }}</h4>
            <p class="text-muted mb-0 small d-none d-md-block">Here's what's happening at {{ $branding['company_name'] }} today.</p>
        </div>
        <div class="d-flex flex-wrap gap-1 gap-md-2 w-100 w-sm-auto">
            <a href="{{ route('admin.products.create') }}" data-turbo-frame="admin-content" class="btn btn-danger btn-sm rounded-pill px-2 px-md-3 flex-grow-1 flex-sm-grow-0">
                <i class="bi bi-plus-lg me-1"></i> Add Product
            </a>
            <a href="{{ route('admin.orders.index') }}" class="btn btn-outline-secondary btn-sm rounded-pill px-2 px-md-3">
                <i class="bi bi-cart3 me-1"></i> Orders
            </a>
            <a href="{{ route('admin.slides.index') }}" class="btn btn-outline-secondary btn-sm rounded-pill px-2 px-md-3 d-none d-sm-inline-flex">
                <i class="bi bi-images me-1"></i> Hero Slides
            </a>
        </div>
    </div>
</div>

{{-- Pending actions alert --}}
@if($pendingActions > 0)
<div class="alert alert-warning border-0 rounded-4 shadow-sm d-flex align-items-center gap-3 mb-4" role="alert">
    <div class="rounded-circle bg-warning bg-opacity-25 text-warning d-flex align-items-center justify-content-center flex-shrink-0" style="width:42px;height:42px;">
        <i class="bi bi-bell-fill"></i>
    </div>
    <div class="flex-grow-1">
        <strong>{{ $pendingActions }} item{{ $pendingActions > 1 ? 's' : '' }} need your attention</strong>
        <div class="small mt-1">
            @if($pendingOrders > 0)<span class="me-3"><i class="bi bi-cart3 me-1"></i>{{ $pendingOrders }} pending order{{ $pendingOrders > 1 ? 's' : '' }}</span>@endif
            @if($pendingBookings > 0)<span class="me-3"><i class="bi bi-tools me-1"></i>{{ $pendingBookings }} repair booking{{ $pendingBookings > 1 ? 's' : '' }}</span>@endif
            @if($pendingQuotations > 0)<span class="me-3"><i class="bi bi-chat-quote me-1"></i>{{ $pendingQuotations }} quotation{{ $pendingQuotations > 1 ? 's' : '' }}</span>@endif
            @if($unreadMessages > 0)<span><i class="bi bi-envelope me-1"></i>{{ $unreadMessages }} unread message{{ $unreadMessages > 1 ? 's' : '' }}</span>@endif
        </div>
    </div>
</div>
@endif

{{-- Primary KPI row --}}
<div class="row g-2 g-md-3 mb-2 mb-md-3">
    <div class="col-6 col-sm-6 col-xl-3">
        <div class="card dashboard-stat-card p-2 p-md-4 h-100">
            <div class="d-flex justify-content-between align-items-start gap-1">
                <div class="dashboard-stat-body min-w-0">
                    <span class="dashboard-stat-label">Total Revenue</span>
                    <h3 class="dashboard-stat-value">KSh {{ number_format($totalRevenue) }}</h3>
                    <span class="dashboard-stat-sub {{ $revenueChange >= 0 ? 'text-success' : 'text-danger' }}">
                        <i class="bi bi-{{ $revenueChange >= 0 ? 'arrow-up-short' : 'arrow-down-short' }}"></i>
                        {{ abs($revenueChange) }}%<span class="d-none d-md-inline"> vs last month</span>
                    </span>
                </div>
                <div class="dashboard-stat-icon bg-success-subtle text-success flex-shrink-0"><i class="bi bi-wallet2"></i></div>
            </div>
        </div>
    </div>
    <div class="col-6 col-sm-6 col-xl-3">
        <div class="card dashboard-stat-card p-2 p-md-4 h-100">
            <div class="d-flex justify-content-between align-items-start gap-1">
                <div class="dashboard-stat-body min-w-0">
                    <span class="dashboard-stat-label">This Month</span>
                    <h3 class="dashboard-stat-value">KSh {{ number_format($thisMonthRevenue) }}</h3>
                    <span class="dashboard-stat-sub text-muted">{{ $thisMonthOrders }} order{{ $thisMonthOrders !== 1 ? 's' : '' }}</span>
                </div>
                <div class="dashboard-stat-icon bg-danger-subtle text-danger flex-shrink-0"><i class="bi bi-graph-up-arrow"></i></div>
            </div>
        </div>
    </div>
    <div class="col-6 col-sm-6 col-xl-3">
        <div class="card dashboard-stat-card p-2 p-md-4 h-100">
            <div class="d-flex justify-content-between align-items-start gap-1">
                <div class="dashboard-stat-body min-w-0">
                    <span class="dashboard-stat-label">Total Orders</span>
                    <h3 class="dashboard-stat-value">{{ number_format($totalOrders) }}</h3>
                    <span class="dashboard-stat-sub text-warning">
                        <span class="d-inline d-xl-none">{{ $pendingOrders }}p · {{ $processingOrders }} active</span>
                        <span class="d-none d-xl-inline">{{ $pendingOrders }} pending · {{ $processingOrders }} in progress</span>
                    </span>
                </div>
                <div class="dashboard-stat-icon bg-warning-subtle text-warning flex-shrink-0"><i class="bi bi-cart3"></i></div>
            </div>
        </div>
    </div>
    <div class="col-6 col-sm-6 col-xl-3">
        <div class="card dashboard-stat-card p-2 p-md-4 h-100">
            <div class="d-flex justify-content-between align-items-start gap-1">
                <div class="dashboard-stat-body min-w-0">
                    <span class="dashboard-stat-label">Customers</span>
                    <h3 class="dashboard-stat-value">{{ number_format($totalCustomers) }}</h3>
                    <span class="dashboard-stat-sub text-muted d-none d-sm-inline">Registered accounts</span>
                    <span class="dashboard-stat-sub text-muted d-sm-none">Accounts</span>
                </div>
                <div class="dashboard-stat-icon bg-primary-subtle text-primary flex-shrink-0"><i class="bi bi-people"></i></div>
            </div>
        </div>
    </div>
</div>

{{-- Secondary KPI row --}}
<div class="row g-2 g-md-3 mb-3 mb-md-4">
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card dashboard-mini-stat p-2 p-md-3 text-center h-100">
            <div class="dashboard-mini-stat-icon text-danger mx-auto mb-1 mb-md-2"><i class="bi bi-bicycle"></i></div>
            <div class="dashboard-mini-stat-value fw-bold text-secondary">{{ $totalProducts }}</div>
            <div class="small text-muted" style="font-size:0.7rem;">Products</div>
            <div class="small text-muted d-none d-md-block">{{ $totalBikes }} bikes</div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card dashboard-mini-stat p-2 p-md-3 text-center h-100">
            <div class="dashboard-mini-stat-icon text-info mx-auto mb-1 mb-md-2"><i class="bi bi-tools"></i></div>
            <div class="dashboard-mini-stat-value fw-bold text-secondary">{{ $pendingBookings }}</div>
            <div class="small text-muted" style="font-size:0.7rem;">Repairs</div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card dashboard-mini-stat p-2 p-md-3 text-center h-100">
            <div class="dashboard-mini-stat-icon text-warning mx-auto mb-1 mb-md-2"><i class="bi bi-chat-quote"></i></div>
            <div class="dashboard-mini-stat-value fw-bold text-secondary">{{ $pendingQuotations }}</div>
            <div class="small text-muted" style="font-size:0.7rem;">Quotes</div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card dashboard-mini-stat p-2 p-md-3 text-center h-100">
            <div class="dashboard-mini-stat-icon text-success mx-auto mb-1 mb-md-2"><i class="bi bi-images"></i></div>
            <div class="dashboard-mini-stat-value fw-bold text-secondary">{{ $activeSlides }}</div>
            <div class="small text-muted" style="font-size:0.7rem;">Slides</div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card dashboard-mini-stat p-2 p-md-3 text-center h-100">
            <div class="dashboard-mini-stat-icon text-primary mx-auto mb-1 mb-md-2"><i class="bi bi-journal-text"></i></div>
            <div class="dashboard-mini-stat-value fw-bold text-secondary">{{ $publishedPosts }}</div>
            <div class="small text-muted" style="font-size:0.7rem;">Blog</div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card dashboard-mini-stat p-2 p-md-3 text-center h-100 {{ $lowStockCount > 0 ? 'border-warning' : '' }}">
            <div class="dashboard-mini-stat-icon text-danger mx-auto mb-1 mb-md-2"><i class="bi bi-exclamation-triangle"></i></div>
            <div class="dashboard-mini-stat-value fw-bold text-secondary">{{ $lowStockCount }}</div>
            <div class="small text-muted" style="font-size:0.7rem;">Low Stock</div>
        </div>
    </div>
</div>

{{-- Charts row --}}
<div class="row g-2 g-md-4 mb-3 mb-md-4">
    <div class="col-lg-8">
        <div class="card dashboard-panel p-3 p-md-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <h6 class="fw-bold text-secondary mb-0">Revenue Overview</h6>
                    <span class="small text-muted">Paid orders — {{ $year }}</span>
                </div>
                <span class="badge bg-danger-subtle text-danger rounded-pill">KSh</span>
            </div>
            <div class="dashboard-chart-wrap" style="height:280px;position:relative;">
                <canvas id="revenueChart"></canvas>
                @unless($hasRevenueData)
                <div class="dashboard-chart-empty">
                    <i class="bi bi-bar-chart-line fs-2 text-muted mb-2 d-block"></i>
                    <p class="small text-muted mb-0">No paid orders yet this year.<br>Revenue will appear here once payments are recorded.</p>
                </div>
                @endunless
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card dashboard-panel p-3 p-md-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <h6 class="fw-bold text-secondary mb-0">Order Volume</h6>
                    <span class="small text-muted">All orders — {{ $year }}</span>
                </div>
            </div>
            <div class="dashboard-chart-wrap" style="height:280px;position:relative;">
                <canvas id="ordersChart"></canvas>
                @unless($hasOrderData)
                <div class="dashboard-chart-empty">
                    <i class="bi bi-cart-x fs-2 text-muted mb-2 d-block"></i>
                    <p class="small text-muted mb-0">No orders placed yet this year.</p>
                </div>
                @endunless
            </div>
        </div>
    </div>
</div>

{{-- Status breakdown + low stock --}}
<div class="row g-2 g-md-4 mb-3 mb-md-4">
    <div class="col-md-4">
        <div class="card dashboard-panel p-3 p-md-4 h-100">
            <h6 class="fw-bold text-secondary mb-3">Order Status</h6>
            @if(count($orderStatusBreakdown) > 0)
                <div style="height:200px;position:relative;">
                    <canvas id="orderStatusChart"></canvas>
                </div>
                <ul class="list-unstyled mt-3 mb-0">
                    @foreach($orderStatusBreakdown as $status => $count)
                    <li class="d-flex justify-content-between small py-1 border-bottom border-light">
                        <span class="text-capitalize text-muted">{{ str_replace('_', ' ', $status) }}</span>
                        <span class="fw-bold text-secondary">{{ $count }}</span>
                    </li>
                    @endforeach
                </ul>
            @else
                <div class="text-center py-5 text-muted">
                    <i class="bi bi-pie-chart fs-2 d-block mb-2 opacity-50"></i>
                    <p class="small mb-0">No orders to display</p>
                </div>
            @endif
        </div>
    </div>
    <div class="col-md-4">
        <div class="card dashboard-panel p-3 p-md-4 h-100">
            <h6 class="fw-bold text-secondary mb-3">Repair Bookings</h6>
            @if(count($bookingStatusBreakdown) > 0)
                <ul class="list-unstyled mb-0">
                    @foreach($bookingStatusBreakdown as $status => $count)
                    <li class="d-flex align-items-center justify-content-between py-2 border-bottom border-light">
                        <span class="text-capitalize small text-muted">{{ $status }}</span>
                        <span class="badge bg-{{ $status === 'completed' ? 'success' : ($status === 'confirmed' ? 'info' : 'warning') }} bg-opacity-10 text-{{ $status === 'completed' ? 'success' : ($status === 'confirmed' ? 'info' : 'warning') }} rounded-pill">{{ $count }}</span>
                    </li>
                    @endforeach
                </ul>
                <a href="{{ route('admin.bookings.index') }}" class="btn btn-sm btn-outline-secondary rounded-pill w-100 mt-3">Manage Bookings</a>
            @else
                <div class="text-center py-5 text-muted">
                    <i class="bi bi-tools fs-2 d-block mb-2 opacity-50"></i>
                    <p class="small mb-0">No repair bookings yet</p>
                </div>
            @endif
        </div>
    </div>
    <div class="col-md-4">
        <div class="card dashboard-panel p-3 p-md-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="fw-bold text-secondary mb-0">Low Stock Alert</h6>
                @if($lowStockCount > 0)
                <span class="badge bg-warning text-dark rounded-pill">{{ $lowStockCount }}</span>
                @endif
            </div>
            @if($lowStockProducts->count() > 0)
                <ul class="list-unstyled mb-0">
                    @foreach($lowStockProducts as $product)
                    <li class="d-flex align-items-center justify-content-between py-2 border-bottom border-light">
                        <div class="small text-truncate me-2" style="max-width:70%;">
                            <a href="{{ route('admin.products.edit', $product->id) }}" class="text-decoration-none text-secondary fw-semibold">{{ $product->name }}</a>
                        </div>
                        <span class="badge bg-danger bg-opacity-10 text-danger rounded-pill">{{ $product->stock_quantity }} left</span>
                    </li>
                    @endforeach
                </ul>
                <a href="{{ route('admin.products.index') }}" class="btn btn-sm btn-outline-danger rounded-pill w-100 mt-3">View All Products</a>
            @else
                <div class="text-center py-5 text-muted">
                    <i class="bi bi-check-circle fs-2 d-block mb-2 text-success opacity-75"></i>
                    <p class="small mb-0">All products are well stocked</p>
                </div>
            @endif
        </div>
    </div>
</div>

{{-- Activity tables --}}
<div class="row g-2 g-md-4">
    <div class="col-lg-6">
        <div class="card dashboard-panel p-3 p-md-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3 border-bottom pb-2">
                <h6 class="fw-bold text-secondary mb-0"><i class="bi bi-cart3 me-2 text-danger"></i>Recent Orders</h6>
                <a href="{{ route('admin.orders.index') }}" class="text-danger text-decoration-none small fw-semibold">View All</a>
            </div>
            @if($recentOrders->count() > 0)
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0 dashboard-table">
                    <thead>
                        <tr>
                            <th>Order</th>
                            <th>Customer</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($recentOrders as $ord)
                        <tr>
                            <td><a href="{{ route('admin.orders.show', $ord->id) }}" class="fw-bold text-decoration-none text-secondary">#{{ $ord->order_number }}</a></td>
                            <td class="text-muted small text-truncate" style="max-width:100px;">{{ $ord->user->name ?? $ord->phone }}</td>
                            <td class="fw-semibold small">KSh {{ number_format($ord->total_amount) }}</td>
                            <td><span class="badge status-badge status-{{ $ord->status }}">{{ ucfirst($ord->status) }}</span></td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
            @else
            <div class="dashboard-empty-state">
                <i class="bi bi-cart3"></i>
                <p>No orders yet</p>
                <span class="small">Orders from customers will appear here.</span>
            </div>
            @endif
        </div>
    </div>

    <div class="col-lg-6">
        <div class="card dashboard-panel p-3 p-md-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3 border-bottom pb-2">
                <h6 class="fw-bold text-secondary mb-0"><i class="bi bi-tools me-2 text-info"></i>Recent Repair Bookings</h6>
                <a href="{{ route('admin.bookings.index') }}" class="text-danger text-decoration-none small fw-semibold">View All</a>
            </div>
            @if($recentBookings->count() > 0)
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0 dashboard-table">
                    <thead>
                        <tr>
                            <th>Customer</th>
                            <th>Bike</th>
                            <th>Date</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($recentBookings as $bk)
                        <tr>
                            <td><a href="{{ route('admin.bookings.show', $bk->id) }}" class="fw-bold text-decoration-none text-secondary">{{ $bk->name }}</a></td>
                            <td class="text-muted small">{{ $bk->bike_type }}</td>
                            <td class="text-muted small">{{ $bk->preferred_date->format('d M Y') }}</td>
                            <td><span class="badge status-badge status-{{ $bk->status }}">{{ ucfirst($bk->status) }}</span></td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
            @else
            <div class="dashboard-empty-state">
                <i class="bi bi-tools"></i>
                <p>No repair bookings yet</p>
                <span class="small">Service requests will appear here.</span>
            </div>
            @endif
        </div>
    </div>

    <div class="col-12">
        <div class="card dashboard-panel p-3 p-md-4">
            <div class="d-flex justify-content-between align-items-center mb-3 border-bottom pb-2">
                <h6 class="fw-bold text-secondary mb-0"><i class="bi bi-chat-quote me-2 text-warning"></i>Recent Quotation Requests</h6>
                <a href="{{ route('admin.quotations.index') }}" class="text-danger text-decoration-none small fw-semibold">View All</a>
            </div>
            @if($recentQuotations->count() > 0)
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0 dashboard-table">
                    <thead>
                        <tr>
                            <th>Customer</th>
                            <th>Product</th>
                            <th>Phone</th>
                            <th>Date</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($recentQuotations as $quote)
                        <tr>
                            <td class="fw-semibold small">{{ $quote->name }}</td>
                            <td class="text-muted small">{{ $quote->product->name ?? '—' }}</td>
                            <td class="text-muted small">{{ $quote->phone }}</td>
                            <td class="text-muted small">{{ $quote->created_at->format('d M Y') }}</td>
                            <td><span class="badge status-badge status-{{ $quote->status }}">{{ ucfirst($quote->status) }}</span></td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
            @else
            <div class="dashboard-empty-state py-4">
                <i class="bi bi-chat-quote"></i>
                <p>No quotation requests yet</p>
                <span class="small">Price quote requests from the marketplace will appear here.</span>
            </div>
            @endif
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script data-turbo-eval="true">
function initDashboardCharts() {
    if (!document.getElementById('revenueChart')) return;

    ['revenueChart', 'ordersChart', 'orderStatusChart'].forEach(function (id) {
        const el = document.getElementById(id);
        if (el && Chart.getChart(el)) Chart.getChart(el).destroy();
    });

    const months = @json($months);
    const revenueData = @json($revenueTotals);
    const orderData = @json($orderTotals);
    const orderStatus = @json(array_values($orderStatusBreakdown));
    const orderStatusLabels = @json($orderStatusLabels);

    const chartDefaults = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { display: false } },
    };

    const revenueMax = Math.max(...revenueData, 0);
    new Chart(document.getElementById('revenueChart'), {
        type: 'line',
        data: {
            labels: months,
            datasets: [{
                label: 'Revenue (KSh)',
                data: revenueData,
                borderColor: '#f97316',
                backgroundColor: 'rgba(249, 115, 22, 0.08)',
                borderWidth: 2.5,
                fill: true,
                tension: 0.4,
                pointBackgroundColor: '#f97316',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: revenueData.some(v => v > 0) ? 4 : 0,
            }]
        },
        options: {
            ...chartDefaults,
            scales: {
                x: { grid: { display: false }, ticks: { font: { size: 11 } } },
                y: {
                    beginAtZero: true,
                    suggestedMax: revenueMax > 0 ? undefined : 10000,
                    grid: { color: 'rgba(0,0,0,0.05)' },
                    ticks: {
                        font: { size: 11 },
                        callback: v => 'KSh ' + Number(v).toLocaleString(),
                    }
                }
            }
        }
    });

    const orderMax = Math.max(...orderData, 0);
    new Chart(document.getElementById('ordersChart'), {
        type: 'bar',
        data: {
            labels: months,
            datasets: [{
                label: 'Orders',
                data: orderData,
                backgroundColor: 'rgba(17, 17, 22, 0.75)',
                borderRadius: 6,
                barThickness: 14,
            }]
        },
        options: {
            ...chartDefaults,
            scales: {
                x: { grid: { display: false }, ticks: { font: { size: 10 } } },
                y: {
                    beginAtZero: true,
                    suggestedMax: orderMax > 0 ? undefined : 5,
                    ticks: { stepSize: 1, font: { size: 11 } },
                    grid: { color: 'rgba(0,0,0,0.05)' },
                }
            }
        }
    });

    @if(count($orderStatusBreakdown) > 0)
    new Chart(document.getElementById('orderStatusChart'), {
        type: 'doughnut',
        data: {
            labels: orderStatusLabels,
            datasets: [{
                data: orderStatus,
                backgroundColor: ['#f97316', '#3b82f6', '#22c55e', '#eab308', '#ef4444', '#8b5cf6'],
                borderWidth: 0,
                hoverOffset: 6,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '65%',
            plugins: { legend: { display: false } },
        }
    });
    @endif
}

document.addEventListener('DOMContentLoaded', initDashboardCharts);
document.addEventListener('turbo:page-ready', initDashboardCharts);
</script>
@endsection
