@props(['dateFrom', 'dateTo'])

<div x-data="{ showFilterModal: false, showExportModal: false, showPrintModal: false }">
    <x-basics.dropdown align="right" width="w-56" :closeOnClick="true">
        <x-slot name="trigger">
            <button type="button" class="p-2 rounded hover:bg-gray-100" aria-label="Open menu">
                <i class="ph ph-dots-three-outline-vertical text-xl"></i>
            </button>
        </x-slot>

        <x-slot name="content">
            <x-basics.dropdown-item icon="ph ph-magnifying-glass" @click="showFilterModal = true">
                Filtrer
            </x-basics.dropdown-item>

            <x-basics.dropdown-item icon="ph ph-arrow-clockwise" href="{{ route('reports.inventory-intelligence') }}">
                Reset
            </x-basics.dropdown-item>

            <x-basics.dropdown-item icon="ph ph-printer" @click="showPrintModal = true">
                Imprimer
            </x-basics.dropdown-item>

            {{-- <x-basics.dropdown-item icon="ph ph-download" @click="showExportModal = true">
                Exporter
            </x-basics.dropdown-item> --}}

            <x-basics.dropdown-item icon="ph ph-info" href="{{ route('reports.inventory-intelligence.guide') }}">
                Guide d'interprétation
            </x-basics.dropdown-item>
        </x-slot>
    </x-basics.dropdown>



    <!-- Filter Modal -->
    <form action="{{ route('reports.inventory-intelligence') }}" method="GET">
        <x-basics.modal show="showFilterModal" title="Filtrer le rapport"
            description="Choisissez la période pour le filtrage du rapport" size="lg">

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <x-basics.input label="Du" type="date" name="date_from" id="date_from" required
                        value="{{ $dateFrom ?? '' }}" />
                </div>
                <div>
                    <x-basics.input label="Au" type="date" name="date_to" id="date_to" required
                        value="{{ $dateTo ?? '' }}" />
                </div>
            </div>


            @slot('footer')
                <x-basics.button type="submit" variant="primary" class="w-full mb-3">
                    <i class="ph ph-magnifying-glass mr-2"></i>
                    Filtrer
                </x-basics.button>
            @endslot
        </x-basics.modal>
    </form>


    <!-- Export Report Modal -->
    <form id="export-form" action="{{ route('reports.inventory-intelligence.export') }}" method="POST" class="space-y-4">
        @csrf
        <x-basics.modal show="showExportModal" title="Générer le rapport"
            description="Exporter le rapport d'intelligence d'inventaire">

            <input type="hidden" name="export_date_from" value="{{ $dateFrom }}">
            <input type="hidden" name="export_date_to" value="{{ $dateTo }}">

            <div>
                <label for="export_format" class="block text-sm font-medium text-gray-700 mb-2">
                    Format d'export <span class="text-red-500">*</span>
                </label>
                <select name="export_format" id="export_format" required
                    class="block w-full h-11 rounded-lg border-0 py-2.5 px-4 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-1 focus:ring-inset focus:ring-indigo-600">
                    <option value="">Choisir un format</option>
                    <option value="csv">CSV</option>
                    <option value="excel">Excel</option>
                    <option value="pdf">PDF</option>
                </select>
            </div>

            @slot('footer')
                <x-basics.button type="submit" variant="primary" id="export-button" class="w-full">
                    <i class="ph ph-download mr-2"></i>
                    <span id="export-text">Exporter le rapport</span>
                    <span id="export-loading" class="hidden">
                        <i class="ph ph-spinner animate-spin mr-2"></i>
                        Génération en cours...
                    </span>
                </x-basics.button>
            @endslot
        </x-basics.modal>

    </form>

    <!-- Print Modal -->
    <form action="{{ route('reports.inventory-intelligence.print') }}" method="POST" target="_blank">
        @csrf
        <x-basics.modal show="showPrintModal" title="Imprimer le rapport"
            description="Le rapport s'ouvrira dans une nouvelle fenêtre avec la boîte de dialogue d'impression">

            <input type="hidden" name="print_date_from" value="{{ $dateFrom }}">
            <input type="hidden" name="print_date_to" value="{{ $dateTo }}">

            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div class="flex items-start">
                    <i class="ph ph-info text-blue-600 text-xl mr-3 mt-1"></i>
                    <div class="text-sm text-blue-900">
                        <p class="font-medium mb-1">Instructions d'impression</p>
                        <ul class="list-disc list-inside space-y-1 text-blue-800">
                            <li>Le rapport s'ouvrira dans une nouvelle fenêtre</li>
                            <li>La boîte de dialogue d'impression s'affichera automatiquement</li>
                            <li>Choisissez votre imprimante et les paramètres souhaités</li>
                            <li>Vous pouvez également enregistrer en PDF depuis la boîte de dialogue</li>
                        </ul>
                    </div>
                </div>
            </div>

            @slot('footer')
                <x-basics.button type="submit" variant="primary" class="w-full mb-3">
                    <i class="ph ph-printer mr-2"></i>
                    Ouvrir l'aperçu d'impression
                </x-basics.button>
            @endslot
        </x-basics.modal>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('Inventory Dropdown script loaded');
    
    // Use event delegation to handle form submission
    document.addEventListener('submit', function(e) {
        if (e.target && e.target.id === 'export-form') {
            console.log('Export form submitted via event delegation');
            
            // Show loading state
            const exportButton = document.getElementById('export-button');
            const exportText = document.getElementById('export-text');
            const exportLoading = document.getElementById('export-loading');
            
            console.log('Export elements found:', {
                button: !!exportButton,
                text: !!exportText,
                loading: !!exportLoading
            });
            
            if (exportButton && exportText && exportLoading) {
                exportButton.disabled = true;
                exportText.classList.add('hidden');
                exportLoading.classList.remove('hidden');
                
                // Submit form via fetch to handle response better
                e.preventDefault();
                
                const formData = new FormData(e.target);
                console.log('Form data:', Object.fromEntries(formData));
                
                fetch(e.target.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                    }
                })
                .then(response => {
                    console.log('Response received:', response);
                    console.log('Response status:', response.status);
                    console.log('Response headers:', response.headers);
                    
                    if (response.ok) {
                        // Check if it's a file download
                        const contentType = response.headers.get('content-type');
                        console.log('Content type:', contentType);
                        
                        if (contentType && contentType.includes('application/pdf')) {
                            // Handle PDF download
                            return response.blob().then(blob => {
                                console.log('PDF blob created, size:', blob.size);
                                const url = window.URL.createObjectURL(blob);
                                const a = document.createElement('a');
                                a.href = url;
                                a.download = 'inventory_intelligence_report.pdf';
                                document.body.appendChild(a);
                                a.click();
                                window.URL.revokeObjectURL(url);
                                document.body.removeChild(a);
                                console.log('PDF download triggered');
                            });
                        } else {
                            // Handle other responses
                            return response.text().then(text => {
                                console.log('Response text:', text);
                            });
                        }
                    } else {
                        throw new Error('Export failed: ' + response.status);
                    }
                })
                .catch(error => {
                    console.error('Export error:', error);
                    alert('Erreur lors de l\'export: ' + error.message);
                })
                .finally(() => {
                    // Reset loading state
                    exportButton.disabled = false;
                    exportText.classList.remove('hidden');
                    exportLoading.classList.add('hidden');
                });
            } else {
                console.error('Export elements not found');
            }
        }
    });
});
</script>
