<div x-data="salesPerformanceDashboard()" x-init="init()">
    <!-- Header -->
    <x-dashboard.breadcrumb :items="[
        'Dashboard' => route('home'),
        'Rapports' => route('reports.business-intelligence'),
        'Performance des ventes du ' .
        ($dateFrom ? \Carbon\Carbon::parse($dateFrom)->format('d/m/Y') : ' - ') .
        ' au ' .
        ($dateTo ? \Carbon\Carbon::parse($dateTo)->format('d/m/Y') : ' - ') => null,
    ]">
        <x-slot name="action">
            <x-dashboard.reports.sales-dropdown :dateFrom="$dateFrom" :dateTo="$dateTo" />
        </x-slot>
    </x-dashboard.breadcrumb>

    <!-- Sales Performance Overview Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mt-6 mb-8">
        <!-- Total Sales -->
        <div class="bg-gradient-to-br from-blue-50 to-blue-100 border border-blue-200 rounded-xl p-6 shadow-sm">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-blue-600 text-sm font-medium">Total Ventes</p>
                    <p class="text-xl font-bold text-blue-800">
                        {{ number_format($salesSummary['total_sales'], 0, ',', ' ') }}
                    </p>
                    <p class="text-sm text-gray-600">
                        {{ $salesSummary['total_sales'] }} commandes
                    </p>
                </div>
                <div class="w-12 h-12 bg-blue-500 rounded-lg flex items-center justify-center">
                    <i class="ph ph-shopping-cart text-white text-xl"></i>
                </div>
            </div>
        </div>

        <!-- Total Revenue -->
        <div class="bg-gradient-to-br from-green-50 to-green-100 border border-green-200 rounded-xl p-6 shadow-sm">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-green-600 text-sm font-medium">Chiffre d'Affaires</p>
                    <p class="font-bold text-green-800">
                        {{ number_format($salesSummary['total_revenue'], 0, ',', ' ') }}
                        {{ \App\Models\Setting::DEFAULT_CURRENCY }}
                    </p>
                    <p class="text-sm text-gray-600">
                        Moyenne: {{ number_format($salesSummary['average_sale'], 0, ',', ' ') }}
                        {{ \App\Models\Setting::DEFAULT_CURRENCY }}
                    </p>
                </div>
                <div class="w-12 h-12 bg-green-500 rounded-lg flex items-center justify-center">
                    <i class="ph ph-credit-card text-white text-xl"></i>
                </div>
            </div>
        </div>

        <!-- Active Customers -->
        <div class="bg-gradient-to-br from-purple-50 to-purple-100 border border-purple-200 rounded-xl p-6 shadow-sm">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-purple-600 text-sm font-medium">Clients Actifs</p>
                    <p class="font-bold text-purple-800">
                        {{ number_format($customerMetrics['active_customers'], 0, ',', ' ') }}
                    </p>
                    <p class="text-sm text-gray-600">
                        {{ $customerMetrics['new_customers'] }} nouveaux
                    </p>
                </div>
                <div class="w-12 h-12 bg-purple-500 rounded-lg flex items-center justify-center">
                    <i class="ph ph-users text-white text-xl"></i>
                </div>
            </div>
        </div>

        <!-- Top Performer -->
        <div class="bg-gradient-to-br from-orange-50 to-orange-100 border border-orange-200 rounded-xl p-6 shadow-sm">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-orange-600 text-sm font-medium">Meilleur Vendeur</p>
                    <p class="font-bold text-orange-800">
                        {{ $salesByUser->first()['user']->firstname ?? '' }}
                        {{ $salesByUser->first()['user']->lastname ?? '' }}
                    </p>
                    <p class="text-sm text-gray-600">
                        {{ number_format($salesByUser->first()['total_revenue'] ?? 0, 0, ',', ' ') }}
                        {{ \App\Models\Setting::DEFAULT_CURRENCY }}
                    </p>
                </div>
                <div class="w-12 h-12 bg-orange-500 rounded-lg flex items-center justify-center">
                    <i class="ph ph-trophy text-white text-xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Sales Trends Chart -->
    <x-basics.card class="mb-8">
        <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="ph ph-chart-line text-blue-600 text-lg"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-gray-900">Tendances des Ventes</h3>
                    <p class="text-sm text-gray-600">Évolution du chiffre d'affaires par jour</p>
                </div>
            </div>
        </div>

        <div class="h-80">
            @if(collect($salesTrends)->sum('total_revenue') > 0)
                <canvas id="salesTrendsChart"></canvas>
            @else
                <div class="flex items-center justify-center h-full">
                    <div class="text-center">
                        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="ph ph-chart-line text-gray-400 text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-medium text-gray-900 mb-2">Aucune donnée de vente</h3>
                        <p class="text-gray-500">Aucune vente trouvée pour la période sélectionnée.</p>
                    </div>
                </div>
            @endif
        </div>
    </x-basics.card>

    <!-- Revenue by Payment Method -->
    <x-basics.card class="mb-8">
        <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                    <i class="ph ph-credit-card text-green-600 text-lg"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-gray-900">Revenus par Méthode de Paiement</h3>
                    <p class="text-sm text-gray-600">Répartition des ventes par type de paiement</p>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <div class="h-80">
                <canvas id="paymentMethodChart"></canvas>
            </div>
            <div class="space-y-4">
                @foreach ($revenueByPaymentMethod->filter(function ($payment) {
        return $payment['total_revenue'] > 0;
    }) as $payment)
                    <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                        <div class="flex items-center gap-3">
                            <div class="w-4 h-4 rounded-full" style="background-color: {{ $payment['color'] }}"></div>
                            <span class="font-medium text-gray-900">{{ $payment['payment_method_name'] }}</span>
                        </div>
                        <div class="text-right">
                            <p class="font-semibold text-gray-900">
                                {{ number_format($payment['total_revenue'], 0, ',', ' ') }}
                                {{ \App\Models\Setting::DEFAULT_CURRENCY }}</p>
                            <p class="text-sm text-gray-600">{{ $payment['percentage'] }}%</p>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
    </x-basics.card>

    @if($topProducts->count() > 0)
    <!-- Top Products -->
    <x-basics.card class="mb-8">
        <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                    <i class="ph ph-package text-purple-600 text-lg"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-gray-900">Produits les Plus Vendus</h3>
                    <p class="text-sm text-gray-600">Top 10 des produits par chiffre d'affaires</p>
                </div>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Produit</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Quantité Vendue</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Chiffre d'Affaires</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Prix
                            Moyen</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @foreach ($topProducts as $product)
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-10 w-10">
                                        <div class="h-10 w-10 rounded-lg bg-gray-200 flex items-center justify-center">
                                            <i class="ph ph-package text-gray-500"></i>
                                        </div>
                                    </div>
                                    <div class="ml-4">
                                        <div class="text-sm font-medium text-gray-900">{{ $product['product']->name }}
                                        </div>
                                        <div class="text-sm text-gray-500">
                                            {{ $product['product']->category->name ?? 'Sans catégorie' }}</div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                {{ number_format($product['total_quantity'], 0, ',', ' ') }}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                {{ number_format($product['total_revenue'], 0, ',', ' ') }}
                                {{ \App\Models\Setting::DEFAULT_CURRENCY }}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                {{ number_format($product['total_revenue'] / max($product['total_quantity'], 1), 0, ',', ' ') }}
                                {{ \App\Models\Setting::DEFAULT_CURRENCY }}
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </x-basics.card>
    @endif

    @if($salesByUser->count() > 0)
    <!-- Sales by User Performance -->
    <x-basics.card class="mb-8">
        <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center">
                    <i class="ph ph-users text-orange-600 text-lg"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-gray-900">Performance des Vendeurs</h3>
                    <p class="text-sm text-gray-600">Classement des vendeurs par chiffre d'affaires</p>
                </div>
            </div>
        </div>

        <div class="space-y-4">
            @foreach ($salesByUser as $index => $userSales)
                <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                    <div class="flex items-center gap-4">
                        <div
                            class="w-8 h-8 rounded-full flex items-center justify-center text-white font-bold
                            @if ($index === 0) bg-yellow-500 @elseif($index === 1) bg-gray-400 @elseif($index === 2) bg-orange-600 @else bg-gray-300 @endif">
                            {{ $index + 1 }}
                        </div>
                        <div>
                            <p class="font-medium text-gray-900">{{ $userSales['user']->firstname }}
                                {{ $userSales['user']->lastname }}</p>
                            <p class="text-sm text-gray-600">{{ $userSales['sales_count'] }} commandes</p>
                        </div>
                    </div>
                    <div class="text-right">
                        <p class="font-semibold text-gray-900">
                            {{ number_format($userSales['total_revenue'], 0, ',', ' ') }}
                            {{ \App\Models\Setting::DEFAULT_CURRENCY }}</p>
                        <p class="text-sm text-gray-600">Moyenne:
                            {{ number_format($userSales['average_sale'], 0, ',', ' ') }}
                            {{ \App\Models\Setting::DEFAULT_CURRENCY }}</p>
                    </div>
                </div>
            @endforeach
        </div>
    </x-basics.card>
    @endif

    @if($salesByType->count() > 0)
    <!-- Sales by Type -->
    <x-basics.card class="mb-8">
        <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center">
                    <i class="ph ph-chart-pie text-indigo-600 text-lg"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-gray-900">Ventes par Type</h3>
                    <p class="text-sm text-gray-600">Répartition des ventes par type de transaction</p>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            @foreach ($salesByType as $type)
                <div class="p-4 bg-gray-50 rounded-lg border border-gray-200">
                    <div class="flex items-center justify-between mb-2">
                        <h4 class="font-medium text-gray-900">{{ $type['sale_type_name'] }}</h4>
                        <span class="text-sm text-gray-600">{{ $type['total_orders'] }} commandes</span>
                    </div>
                    <p class="text-2xl font-bold text-gray-900">
                        {{ number_format($type['total_revenue'], 0, ',', ' ') }}
                        {{ \App\Models\Setting::DEFAULT_CURRENCY }}</p>
                    <p class="text-sm text-gray-600 mt-1">Moyenne:
                        {{ number_format($type['average_order_value'], 0, ',', ' ') }}
                        {{ \App\Models\Setting::DEFAULT_CURRENCY }}</p>
                </div>
            @endforeach
        </div>
    </x-basics.card>
    @endif


    @push('scripts')
        <script src="{{ asset('plugins/chartjs/chart.min.js') }}"></script>
        <script>
            function salesPerformanceDashboard() {
                return {
                    showExportModal: false,
                    chartsInitialized: false,

                    init() {
                        // Wait for DOM to be ready, especially important for wire:navigate
                        this.$nextTick(() => {
                            setTimeout(() => {
                                this.initCharts();
                            }, 100);
                        });
                    },

                    initCharts() {
                        // Prevent double initialization
                        if (this.chartsInitialized) {
                            return;
                        }
                        // Simple currency formatter for JavaScript
                        function formatCurrencyJS(amount) {
                            if (amount === null || amount === undefined) {
                                return '0,00 {{ \App\Models\Setting::DEFAULT_CURRENCY }}';
                            }
                            return new Intl.NumberFormat('fr-FR', {
                                style: 'currency',
                                currency: '{{ \App\Models\Setting::DEFAULT_CURRENCY }}',
                                minimumFractionDigits: 2
                            }).format(amount);
                        }

                        // Destroy existing charts before creating new ones
                        try {
                            if (window.salesTrendsChart) {
                                if (typeof window.salesTrendsChart.destroy === 'function') {
                                    window.salesTrendsChart.destroy();
                                }
                                window.salesTrendsChart = null;
                            }
                        } catch (e) {
                            console.log('Error destroying sales trends chart:', e);
                        }

                        try {
                            if (window.paymentMethodChart) {
                                if (typeof window.paymentMethodChart.destroy === 'function') {
                                    window.paymentMethodChart.destroy();
                                }
                                window.paymentMethodChart = null;
                            }
                        } catch (e) {
                            console.log('Error destroying payment method chart:', e);
                        }

                        try {
                            // Sales Trends Chart
                            const salesTrendsCtx = document.getElementById('salesTrendsChart');
                            if (salesTrendsCtx) {
                                // Debug: Log the data being used
                                console.log('Sales Trends Data:', {!! json_encode($salesTrends) !!});
                                console.log('Labels:', {!! json_encode(collect($salesTrends)->pluck('date_label')) !!});
                                console.log('Revenue Data:', {!! json_encode(collect($salesTrends)->pluck('total_revenue')) !!});
                                
                                // Clear the canvas
                                salesTrendsCtx.getContext('2d').clearRect(0, 0, salesTrendsCtx.width, salesTrendsCtx.height);

                                window.salesTrendsChart = new Chart(salesTrendsCtx, {
                                    type: 'line',
                                    data: {
                                        labels: {!! json_encode(collect($salesTrends)->pluck('date_label')) !!},
                                        datasets: [{
                                            label: 'Chiffre d\'Affaires ({{ \App\Models\Setting::DEFAULT_CURRENCY }})',
                                            data: {!! json_encode(collect($salesTrends)->pluck('total_revenue')) !!},
                                            borderColor: 'rgb(59, 130, 246)',
                                            backgroundColor: 'rgba(59, 130, 246, 0.1)',
                                            tension: 0.4,
                                            fill: true
                                        }]
                                    },
                                    options: {
                                        responsive: true,
                                        maintainAspectRatio: false,
                                        plugins: {
                                            legend: {
                                                display: false
                                            },
                                            tooltip: {
                                                callbacks: {
                                                    label: function(context) {
                                                        return context.dataset.label + ': ' + formatCurrencyJS(
                                                            context.parsed.y);
                                                    }
                                                }
                                            }
                                        },
                                        scales: {
                                            y: {
                                                beginAtZero: true,
                                                ticks: {
                                                    callback: function(value) {
                                                        return formatCurrencyJS(value);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            }
                        } catch (error) {
                            console.error('Error creating sales trends chart:', error);
                        }

                        try {
                            // Payment Method Chart
                            const paymentMethodCtx = document.getElementById('paymentMethodChart');
                            if (paymentMethodCtx) {
                                // Clear the canvas
                                paymentMethodCtx.getContext('2d').clearRect(0, 0, paymentMethodCtx.width, paymentMethodCtx
                                    .height);

                                window.paymentMethodChart = new Chart(paymentMethodCtx, {
                                    type: 'doughnut',
                                    data: {
                                        labels: {!! json_encode(
                                            collect($revenueByPaymentMethod)->filter(function ($payment) {
                                                    return $payment['total_revenue'] > 0;
                                                })->pluck('payment_method_name'),
                                        ) !!},
                                        datasets: [{
                                            data: {!! json_encode(
                                                collect($revenueByPaymentMethod)->filter(function ($payment) {
                                                        return $payment['total_revenue'] > 0;
                                                    })->pluck('total_revenue'),
                                            ) !!},
                                            backgroundColor: {!! json_encode(
                                                collect($revenueByPaymentMethod)->filter(function ($payment) {
                                                        return $payment['total_revenue'] > 0;
                                                    })->pluck('color'),
                                            ) !!},
                                            borderWidth: 2,
                                            borderColor: '#ffffff'
                                        }]
                                    },
                                    options: {
                                        responsive: true,
                                        maintainAspectRatio: false,
                                        plugins: {
                                            legend: {
                                                display: false
                                            },
                                            tooltip: {
                                                callbacks: {
                                                    label: function(context) {
                                                        const total = context.dataset.data.reduce((a, b) => a + b,
                                                            0);
                                                        const percentage = ((context.parsed / total) * 100).toFixed(
                                                            1);
                                                        return context.label + ': ' + formatCurrencyJS(context
                                                                .parsed) +
                                                            ' (' + percentage + '%)';
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            }
                        } catch (error) {
                            console.error('Error creating payment method chart:', error);
                        }
                        
                        // Mark charts as initialized
                        this.chartsInitialized = true;
                    }
                }
            }

            document.addEventListener('alpine:init', () => {
                Alpine.data('salesPerformanceDashboard', salesPerformanceDashboard);
            });

            // Handle Livewire navigation
            document.addEventListener('livewire:navigated', () => {
                // Reset charts initialization flag when navigating
                setTimeout(() => {
                    const dashboardElement = document.querySelector('[x-data*="salesPerformanceDashboard"]');
                    if (dashboardElement && dashboardElement._x_dataStack) {
                        const dashboard = dashboardElement._x_dataStack[0];
                        if (dashboard && typeof dashboard.chartsInitialized !== 'undefined') {
                            dashboard.chartsInitialized = false;
                            dashboard.initCharts();
                        }
                    }
                }, 200);
            });

            // Alternative initialization if Alpine.js doesn't work
            document.addEventListener('DOMContentLoaded', () => {
                setTimeout(() => {
                    if (typeof salesPerformanceDashboard !== 'undefined') {
                        const dashboard = salesPerformanceDashboard();
                        dashboard.init();
                    }
                }, 100);
            });
        </script>
    @endpush
