<x-layouts.admin title="Reports">
    <x-admin.page-header title="Reports" subtitle="{{ $from->format('d M Y') }} – {{ $to->format('d M Y') }}">
        <x-slot:actions>
            <a href="{{ route('admin.reports.export', request()->query()) }}" class="inline-flex items-center gap-2 rounded-lg border border-ink/10 px-4 py-2 text-sm font-medium text-ink/70 transition hover:border-ink/30">
                <i class="fa-solid fa-file-arrow-down text-xs"></i> Export CSV
            </a>
        </x-slot:actions>
    </x-admin.page-header>

    <form method="GET" class="mb-6 flex flex-wrap items-end gap-3">
        <div>
            <x-admin.label value="From" />
            <x-admin.input type="date" name="from" value="{{ $from->format('Y-m-d') }}" />
        </div>
        <div>
            <x-admin.label value="To" />
            <x-admin.input type="date" name="to" value="{{ $to->format('Y-m-d') }}" />
        </div>
        <x-admin.button variant="accent">Apply</x-admin.button>

        <div class="ml-auto flex gap-2">
            @foreach (['7' => '7 Days', '30' => '30 Days', '90' => '90 Days'] as $days => $label)
                <a href="{{ route('admin.reports.index', ['from' => now()->subDays($days - 1)->format('Y-m-d'), 'to' => now()->format('Y-m-d')]) }}" class="rounded-full bg-black/5 px-3 py-1.5 text-xs font-medium text-ink/60 transition hover:bg-black/10">
                    {{ $label }}
                </a>
            @endforeach
        </div>
    </form>

    <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
        <x-admin.stat-card label="Revenue" value="{{ config('niyarasa.currency.symbol') }} {{ number_format($summary['total_revenue']) }}" icon="fa-solid fa-sack-dollar" accent="champagne" />
        <x-admin.stat-card label="Orders" :value="$summary['total_orders']" icon="fa-solid fa-receipt" accent="maroon" />
        <x-admin.stat-card label="Average Order Value" value="{{ config('niyarasa.currency.symbol') }} {{ number_format($summary['average_order_value']) }}" icon="fa-solid fa-chart-simple" accent="champagne" />
    </div>

    <div class="mt-6 grid grid-cols-1 gap-4 lg:grid-cols-2">
        <x-admin.card>
            <h3 class="mb-4 text-sm font-semibold text-ink">Revenue Trend</h3>
            <div class="h-64"><canvas id="revenueTrendChart" role="img" aria-label="Line chart of revenue over the selected date range"></canvas></div>
        </x-admin.card>

        <x-admin.card>
            <h3 class="mb-4 text-sm font-semibold text-ink">Revenue by Category</h3>
            @if ($categoryPerformance->isEmpty())
                <p class="py-16 text-center text-sm text-ink/40">No sales in this range yet.</p>
            @else
                <div class="h-64"><canvas id="categoryChart" role="img" aria-label="Bar chart of revenue by product category"></canvas></div>
            @endif
        </x-admin.card>
    </div>

    <div class="mt-4 grid grid-cols-1 gap-4 lg:grid-cols-3">
        <x-admin.card class="lg:col-span-2" :padded="false">
            <div class="border-b border-black/5 px-5 py-4">
                <h3 class="text-sm font-semibold text-ink">Top Selling Products</h3>
            </div>
            @if ($topProducts->isEmpty())
                <x-admin.empty-state icon="fa-solid fa-shirt" title="No sales in this range yet" />
            @else
                <div class="overflow-x-auto">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Product</th>
                                <th class="text-center">Units Sold</th>
                                <th class="text-right">Revenue</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($topProducts as $i => $product)
                                <tr>
                                    <td class="text-ink/40">{{ $i + 1 }}</td>
                                    <td class="font-medium text-ink">{{ $product->product_name }}</td>
                                    <td class="text-center tabular-nums text-ink/60">{{ $product->total_quantity }}</td>
                                    <td class="text-right tabular-nums font-medium text-ink">{{ config('niyarasa.currency.symbol') }} {{ number_format((float) $product->total_revenue) }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @endif
        </x-admin.card>

        <x-admin.card>
            <h3 class="mb-4 text-sm font-semibold text-ink">Payment Methods</h3>
            <div class="h-56"><canvas id="paymentMethodChart" role="img" aria-label="Doughnut chart of orders by payment method for the selected range"></canvas></div>
        </x-admin.card>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const inkMuted = '#898781';
            const gridline = '#e1e0d9';
            const tooltipBase = { backgroundColor: '#16130f', titleColor: '#faf7f2', bodyColor: '#f1e9dd', padding: 10, cornerRadius: 8 };

            new Chart(document.getElementById('revenueTrendChart'), {
                type: 'line',
                data: {
                    labels: @json($salesTrend['labels']),
                    datasets: [{
                        label: 'Revenue',
                        data: @json($salesTrend['data']),
                        borderColor: '#2a78d6',
                        backgroundColor: 'rgba(42, 120, 214, 0.10)',
                        borderWidth: 2,
                        pointRadius: 0,
                        pointHoverRadius: 5,
                        tension: 0.35,
                        fill: true,
                    }],
                },
                options: {
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: { ...tooltipBase, callbacks: { label: (ctx) => ' {{ config('niyarasa.currency.symbol') }} ' + ctx.parsed.y.toLocaleString() } },
                    },
                    scales: {
                        x: { grid: { display: false }, ticks: { color: inkMuted, maxTicksLimit: 8 } },
                        y: { grid: { color: gridline }, ticks: { color: inkMuted, callback: (v) => v.toLocaleString() }, beginAtZero: true },
                    },
                },
            });

            @if ($categoryPerformance->isNotEmpty())
                new Chart(document.getElementById('categoryChart'), {
                    type: 'bar',
                    data: {
                        labels: @json($categoryPerformance->pluck('category')),
                        datasets: [{
                            label: 'Revenue',
                            data: @json($categoryPerformance->pluck('revenue')),
                            backgroundColor: @json(array_slice(\App\Services\AnalyticsService::CATEGORICAL_COLORS, 0, $categoryPerformance->count())),
                            borderRadius: 4,
                        }],
                    },
                    options: {
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: false },
                            tooltip: { ...tooltipBase, callbacks: { label: (ctx) => ' {{ config('niyarasa.currency.symbol') }} ' + ctx.parsed.y.toLocaleString() } },
                        },
                        scales: {
                            x: { grid: { display: false }, ticks: { color: inkMuted } },
                            y: { grid: { color: gridline }, ticks: { color: inkMuted, callback: (v) => v.toLocaleString() }, beginAtZero: true },
                        },
                    },
                });
            @endif

            new Chart(document.getElementById('paymentMethodChart'), {
                type: 'doughnut',
                data: {
                    labels: @json($paymentMethodBreakdown['labels']),
                    datasets: [{
                        data: @json($paymentMethodBreakdown['data']),
                        backgroundColor: ['#2a78d6', '#eb6834'],
                        borderColor: '#ffffff',
                        borderWidth: 2,
                    }],
                },
                options: {
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'bottom', labels: { color: '#52514e', boxWidth: 10, padding: 12, font: { size: 11 } } },
                        tooltip: tooltipBase,
                    },
                },
            });
        });
    </script>
</x-layouts.admin>
