@props(['stockStatus'])

<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-funnel" @click="showFilterModal = true">
                Filtrer
            </x-basics.dropdown-item>

            <x-basics.dropdown-item icon="ph ph-arrow-clockwise" href="{{ route('reports.stock-report') }}" wire:navigate>
                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.stock-report.guide') }}" wire:navigate>
                Guide d'interprétation
            </x-basics.dropdown-item>
        </x-slot>
    </x-basics.dropdown>

    <!-- Filter Modal -->
    <form action="{{ route('reports.stock-report') }}" method="GET">
        <x-basics.modal show="showFilterModal" title="Filtrer le rapport"
            description="Choisissez le statut du stock pour le filtrage du rapport" size="sm">

            <div>
                <label for="stock_status" class="block text-sm font-medium text-gray-700 mb-2">
                    Statut du Stock
                </label>
                <select name="stock_status" id="stock_status"
                    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="all" {{ $stockStatus == 'all' ? 'selected' : '' }}>Tous les produits</option>
                    <option value="in_stock" {{ $stockStatus == 'in_stock' ? 'selected' : '' }}>En stock</option>
                    <option value="low_stock" {{ $stockStatus == 'low_stock' ? 'selected' : '' }}>Stock faible</option>
                    <option value="out_of_stock" {{ $stockStatus == 'out_of_stock' ? 'selected' : '' }}>En rupture</option>
                </select>
            </div>

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

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

            <input type="hidden" name="export_stock_status" value="{{ $stockStatus }}">

            <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.stock-report.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_stock_status" value="{{ $stockStatus }}">

            <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() {
        document.addEventListener('submit', function(e) {
            if (e.target && e.target.id === 'export-form') {
                const exportButton = document.getElementById('export-button');
                const exportText = document.getElementById('export-text');
                const exportLoading = document.getElementById('export-loading');

                if (exportButton && exportText && exportLoading) {
                    exportButton.disabled = true;
                    exportText.classList.add('hidden');
                    exportLoading.classList.remove('hidden');

                    e.preventDefault();

                    const formData = new FormData(e.target);

                    fetch(e.target.action, {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                            }
                        })
                        .then(response => {
                            if (response.ok) {
                                const contentType = response.headers.get('content-type');

                                if (contentType && contentType.includes('application/pdf')) {
                                    return response.blob().then(blob => {
                                        const url = window.URL.createObjectURL(blob);
                                        const a = document.createElement('a');
                                        a.href = url;
                                        a.download = 'stock_report.pdf';
                                        document.body.appendChild(a);
                                        a.click();
                                        window.URL.revokeObjectURL(url);
                                        document.body.removeChild(a);
                                    });
                                }
                            } else {
                                throw new Error('Export failed: ' + response.status);
                            }
                        })
                        .catch(error => {
                            console.error('Export error:', error);
                            alert('Erreur lors de l\'export: ' + error.message);
                        })
                        .finally(() => {
                            exportButton.disabled = false;
                            exportText.classList.remove('hidden');
                            exportLoading.classList.add('hidden');
                        });
                }
            }
        });
    });
</script>

