<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 Excel files to import products with Arabic and English content</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
                />

                {{-- Arabic File Upload (Primary) --}}
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        <span class="flex items-center gap-2">
                            <span class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-700 text-xs font-bold dark:bg-blue-900 dark:text-blue-300">1</span>
                            Arabic Excel File <span class="text-red-500">*</span>
                        </span>
                        <span class="text-xs text-gray-500 dark:text-gray-400 ml-8">Upload first - Creates products with Arabic content</span>
                    </label>
                    <input
                        type="file"
                        name="arabic_file"
                        id="arabicFileInput"
                        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">Must contain ProductId column for matching</p>
                </div>

                {{-- English File Upload (Secondary) --}}
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        <span class="flex items-center gap-2">
                            <span class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-green-100 text-green-700 text-xs font-bold dark:bg-green-900 dark:text-green-300">2</span>
                            English Excel File <span class="text-gray-400">(Optional)</span>
                        </span>
                        <span class="text-xs text-gray-500 dark:text-gray-400 ml-8">Upload second - Updates products with English content</span>
                    </label>
                    <input
                        type="file"
                        name="english_file"
                        id="englishFileInput"
                        accept=".xlsx,.xls,.csv"
                        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-green-50 file:text-green-700
                            hover:file:bg-green-100
                            dark:file:bg-green-900 dark:file:text-green-200
                            cursor-pointer"
                    >
                    <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">Must contain ProductId column to update existing products</p>
                </div>

                {{-- Preview Info for Arabic --}}
                <div id="arabicPreviewInfo" 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>Arabic File:</strong> <span id="arabicPreviewCount">0</span> products found
                    </p>
                    <p class="text-xs text-blue-600 dark:text-blue-300 mt-1" id="arabicProductIdStatus"></p>
                </div>

                {{-- Preview Info for English --}}
                <div id="englishPreviewInfo" class="hidden mb-4 p-4 bg-green-50 dark:bg-green-900 rounded-md">
                    <p class="text-sm text-green-700 dark:text-green-200">
                        <strong>English File:</strong> <span id="englishPreviewCount">0</span> products found
                    </p>
                    <p class="text-xs text-green-600 dark:text-green-300 mt-1" id="englishProductIdStatus"></p>
                </div>

                {{-- Match Summary --}}
                <div id="matchSummary" class="hidden mb-4 p-4 bg-yellow-50 dark:bg-yellow-900 rounded-md">
                    <p class="text-sm text-yellow-800 dark:text-yellow-200 font-medium">Product ID Match Summary</p>
                    <div class="mt-2 text-xs text-yellow-700 dark:text-yellow-300">
                        <p>New products to create: <span id="newProductsCount" class="font-bold">0</span></p>
                        <p>Products to update: <span id="updateProductsCount" class="font-bold">0</span></p>
                    </div>
                </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 id="currentOperation" class="text-xs text-gray-500 dark:text-gray-500 text-center mt-1"></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 files should include the following columns:</p>

            <div class="mb-4">
                <p class="font-medium text-sm text-blue-700 dark:text-blue-300 mb-2">Required Column:</p>
                <div class="bg-blue-50 dark:bg-blue-900 p-2 rounded text-xs text-gray-600 dark:text-gray-400">
                    <strong>ProductId</strong> - Unique identifier for matching products between Arabic and English files
                </div>
            </div>

            <div class="mb-4">
                <p class="font-medium text-sm text-gray-700 dark:text-gray-300 mb-2">Arabic File Columns:</p>
                <div class="grid grid-cols-2 gap-2 text-xs text-gray-600 dark:text-gray-400">
                    <div>ProductId (required)</div>
                    <div>Image Url</div>
                    <div>Video Url</div>
                    <div>Product Desc (for name_ar, description_ar)</div>
                    <div>Origin Price</div>
                    <div>Discount Price</div>
                    <div>Currency</div>
                    <div>name_ar (explicit name)</div>
                    <div>description_ar (explicit description)</div>
                </div>
            </div>

            <div>
                <p class="font-medium text-sm text-green-700 dark:text-green-300 mb-2">English File Columns:</p>
                <div class="grid grid-cols-2 gap-2 text-xs text-gray-600 dark:text-gray-400">
                    <div>ProductId (required for matching)</div>
                    <div>Product Desc (for name_en, description_en)</div>
                    <div>name_en (explicit name)</div>
                    <div>description_en (explicit description)</div>
                </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 arabicProductsData = [];
        let englishProductsData = [];
        let existingProductIds = new Set();

        // Helper function to read Excel file
        function readExcelFile(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = function(evt) {
                    try {
                        const data = evt.target.result;
                        const workbook = XLSX.read(data, {type: 'binary'});
                        const firstSheet = workbook.SheetNames[0];
                        const jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[firstSheet]);
                        resolve(jsonData);
                    } catch (e) {
                        reject(e);
                    }
                };
                reader.onerror = reject;
                reader.readAsBinaryString(file);
            });
        }

        // Arabic file handler
        document.getElementById('arabicFileInput').addEventListener('change', async function(e) {
            const file = e.target.files[0];
            if (!file) {
                arabicProductsData = [];
                document.getElementById('arabicPreviewInfo').classList.add('hidden');
                updateMatchSummary();
                return;
            }

            try {
                arabicProductsData = await readExcelFile(file);
                document.getElementById('arabicPreviewCount').textContent = arabicProductsData.length;

                // Check for ProductId column
                const hasProductId = arabicProductsData.length > 0 && 'ProductId' in (arabicProductsData[0] || {});
                document.getElementById('arabicProductIdStatus').textContent = hasProductId
                    ? '✓ ProductId column found'
                    : '⚠ ProductId column missing - products will not be matchable';

                document.getElementById('arabicPreviewInfo').classList.remove('hidden');
                updateMatchSummary();
            } catch (error) {
                alert('Error reading Arabic file: ' + error.message);
            }
        });

        // English file handler
        document.getElementById('englishFileInput').addEventListener('change', async function(e) {
            const file = e.target.files[0];
            if (!file) {
                englishProductsData = [];
                document.getElementById('englishPreviewInfo').classList.add('hidden');
                updateMatchSummary();
                return;
            }

            try {
                englishProductsData = await readExcelFile(file);
                document.getElementById('englishPreviewCount').textContent = englishProductsData.length;

                // Check for ProductId column
                const hasProductId = englishProductsData.length > 0 && 'ProductId' in (englishProductsData[0] || {});
                document.getElementById('englishProductIdStatus').textContent = hasProductId
                    ? '✓ ProductId column found'
                    : '⚠ ProductId column missing - cannot update existing products';

                document.getElementById('englishPreviewInfo').classList.remove('hidden');
                updateMatchSummary();
            } catch (error) {
                alert('Error reading English file: ' + error.message);
            }
        });

        // Fetch existing product IDs
        async function fetchExistingProductIds() {
            try {
                const response = await fetch('{{ route('admin.api.products.existing-ids') }}');
                if (response.ok) {
                    const data = await response.json();
                    existingProductIds = new Set(data.product_ids || []);
                }
            } catch (e) {
                console.log('Could not fetch existing product IDs');
            }
        }

        // Update match summary
        function updateMatchSummary() {
            const arabicIds = new Set(arabicProductsData.map(p => p.ProductId).filter(id => id));
            const englishIds = new Set(englishProductsData.map(p => p.ProductId).filter(id => id));

            // Count new products (in Arabic but not in existing)
            let newCount = 0;
            arabicIds.forEach(id => {
                if (!existingProductIds.has(String(id))) {
                    newCount++;
                }
            });

            // Count products that will be updated (English IDs that match Arabic or existing)
            let updateCount = 0;
            englishIds.forEach(id => {
                if (arabicIds.has(id) || existingProductIds.has(String(id))) {
                    updateCount++;
                }
            });

            if (arabicProductsData.length > 0 || englishProductsData.length > 0) {
                document.getElementById('newProductsCount').textContent = newCount;
                document.getElementById('updateProductsCount').textContent = updateCount;
                document.getElementById('matchSummary').classList.remove('hidden');
            } else {
                document.getElementById('matchSummary').classList.add('hidden');
            }

            // Update total
            document.getElementById('importTotal').textContent = arabicProductsData.length + englishProductsData.length;
        }

        // Form submission
        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 (arabicProductsData.length === 0) {
                alert('Please select the Arabic Excel file first');
                return;
            }

            // Fetch existing product IDs for smart matching
            await fetchExistingProductIds();

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

            let imported = 0;
            const batchSize = 50;
            const allOperations = [];

            // First operation: Import Arabic products (creates new or updates _ar fields)
            if (arabicProductsData.length > 0) {
                allOperations.push({
                    language: 'arabic',
                    products: arabicProductsData
                });
            }

            // Second operation: Import English products (updates _en fields)
            if (englishProductsData.length > 0) {
                allOperations.push({
                    language: 'english',
                    products: englishProductsData
                });
            }

            for (const operation of allOperations) {
                const totalBatches = Math.ceil(operation.products.length / batchSize);
                let batchIndex = 0;

                document.getElementById('currentOperation').textContent =
                    `Processing ${operation.language} file...`;

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

                    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,
                                language: operation.language,
                                products: batch,
                                existing_product_ids: Array.from(existingProductIds)
                            })
                        });

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

                        const result = await response.json();
                        imported += batch.length;

                        // Update existing product IDs from response
                        if (result.created_ids && result.created_ids.length > 0) {
                            result.created_ids.forEach(id => existingProductIds.add(String(id)));
                        }

                        document.getElementById('importProgress').textContent = imported;
                        document.getElementById('currentOperation').textContent =
                            `Processing ${operation.language} file: batch ${batchIndex}/${totalBatches}`;

                    } 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!');
        });

        // Fetch existing product IDs on page load
        fetchExistingProductIds().then(() => updateMatchSummary());
    </script>
</x-admin.layout>
