<x-admin.layout title="Import Products">
    <div class="mb-6">
        <h2 class="text-2xl font-bold text-gray-900 dark:text-white">Import Products</h2>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">Upload an Excel file to import products into the system</p>
    </div>

    <div class="max-w-2xl">
        <x-admin.card>
            <form id="importForm">
                @csrf

                <x-admin.form.select
                    name="category_id"
                    label="Category"
                    :options="App\Models\Category::orderBy('name_en')->pluck('name_en', 'id')"
                    required
                />

                <x-admin.form.select
                    name="source"
                    label="Source"
                    :options="['aliexpress' => 'AliExpress', 'amazon' => 'Amazon', 'noon' => 'Noon']"
                    required
                />

                <div class="mb-4">
                    <label for="fileInput" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Excel File (.xlsx, .xls, .csv) <span class="text-red-500">*</span>
                    </label>
                    <input
                        type="file"
                        name="file"
                        id="fileInput"
                        accept=".xlsx,.xls,.csv"
                        required
                        class="block w-full text-sm text-gray-500 dark:text-gray-400
                            file:mr-4 file:py-2 file:px-4
                            file:rounded-md file:border-0
                            file:text-sm file:font-semibold
                            file:bg-blue-50 file:text-blue-700
                            hover:file:bg-blue-100
                            dark:file:bg-blue-900 dark:file:text-blue-200
                            cursor-pointer"
                    >
                    <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">Maximum file size: 10MB</p>
                </div>

                <div id="previewInfo" class="hidden mb-4 p-4 bg-blue-50 dark:bg-blue-900 rounded-md">
                    <p class="text-sm text-blue-700 dark:text-blue-200">
                        <strong>Preview:</strong> <span id="previewCount">0</span> products found in file
                    </p>
                </div>

                <div id="loadingIndicator" class="hidden mb-4">
                    <div class="flex items-center justify-center">
                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                        <span class="ml-3 text-blue-600 dark:text-blue-400">Importing products...</span>
                    </div>
                    <div class="mt-2 text-sm text-gray-600 dark:text-gray-400 text-center">
                        <span id="importProgress">0</span> / <span id="importTotal">0</span> imported
                    </div>
                </div>

                <div class="flex items-center justify-end gap-3">
                    <a href="{{ route('admin.products.index') }}">
                        <x-admin.form.button type="button" variant="outline">Cancel</x-admin.form.button>
                    </a>
                    <x-admin.form.button type="submit" id="submitBtn">Import Products</x-admin.form.button>
                </div>
            </form>
        </x-admin.card>

        <x-admin.card title="Excel File Format" class="mt-6">
            <p class="text-sm text-gray-700 dark:text-gray-300 mb-3">Your Excel file should include the following columns (with headers):</p>
            <div class="grid grid-cols-2 gap-2 text-xs text-gray-600 dark:text-gray-400">
                <div>ProductId</div>
                <div>Image Url</div>
                <div>Video Url</div>
                <div>Product Desc</div>
                <div>Origin Price</div>
                <div>Discount Price</div>
                <div>Discount</div>
                <div>Currency</div>
                <div>Direct linking commission rate (%)</div>
                <div>Estimated direct linking commission</div>
                <div>Indirect linking commission rate (%)</div>
                <div>Estimated indirect linking commission</div>
                <div>Sales180Day</div>
                <div>Positive Feedback</div>
                <div>Promotion Url</div>
                <div>Code Name</div>
                <div>Code Start Time</div>
                <div>Code End Time</div>
                <div>Code Value</div>
                <div>Code Quantity</div>
                <div>Code Minimum Spend</div>
            </div>
        </x-admin.card>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script>
        let productsData = [];

        document.getElementById('fileInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function(evt) {
                const data = evt.target.result;
                const workbook = XLSX.read(data, {type: 'binary'});
                const firstSheet = workbook.SheetNames[0];
                productsData = XLSX.utils.sheet_to_json(workbook.Sheets[firstSheet]);

                if (productsData.length > 0) {
                    console.log('First product data:', productsData[0]);
                    console.log('Available columns:', Object.keys(productsData[0]));
                }

                document.getElementById('previewCount').textContent = productsData.length;
                document.getElementById('previewInfo').classList.remove('hidden');
                document.getElementById('importTotal').textContent = productsData.length;
            };
            reader.readAsBinaryString(file);
        });

        document.getElementById('importForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const categoryId = document.getElementById('category_id').value;
            const source = document.getElementById('source').value;

            if (!categoryId || !source) {
                alert('Please select category and source');
                return;
            }

            if (productsData.length === 0) {
                alert('Please select an Excel file first');
                return;
            }

            document.getElementById('loadingIndicator').classList.remove('hidden');
            document.getElementById('submitBtn').disabled = true;

            const batchSize = 50;
            let imported = 0;

            for (let i = 0; i < productsData.length; i += batchSize) {
                const batch = productsData.slice(i, i + batchSize);

                try {
                    const response = await fetch('{{ route('admin.products.import.store') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify({
                            category_id: categoryId,
                            source: source,
                            products: batch
                        })
                    });

                    if (!response.ok) {
                        const error = await response.json();
                        throw new Error(error.message || 'Import failed');
                    }

                    imported += batch.length;
                    document.getElementById('importProgress').textContent = imported;

                } catch (error) {
                    alert('Error importing batch: ' + error.message);
                    document.getElementById('loadingIndicator').classList.add('hidden');
                    document.getElementById('submitBtn').disabled = false;
                    return;
                }
            }

            window.location.href = '{{ route('admin.products.index') }}?success=' + encodeURIComponent('Successfully imported ' + imported + ' products!');
        });
    </script>
</x-admin.layout>
