{# app/templates/admin/marketplace.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/pagination.html' import pagination %}
{% from 'shared/macros/alerts.html' import alert_dynamic, error_state %}
{% from 'shared/macros/modals.html' import job_details_modal %}
{% from 'shared/macros/tables.html' import table_wrapper, table_header %}
{% from 'shared/macros/headers.html' import page_header_flex, refresh_button %}
{% from 'shared/macros/inputs.html' import number_stepper %}
{% from 'shared/macros/tabs.html' import tabs_nav, tab_button, tab_panel, endtab_panel %}

{% block title %}Marketplace Import{% endblock %}

{% block alpine_data %}adminMarketplace(){% endblock %}

{% block content %}
{% call page_header_flex(title='Marketplace Import', subtitle='Import products from external marketplaces') %}
    {{ refresh_button(onclick='refreshJobs()') }}
{% endcall %}

{{ alert_dynamic(type='success', message_var='successMessage', show_condition='successMessage') }}

{{ error_state('Error', show_condition='error') }}

<!-- Import Form Card with Tabs -->
<div class="mb-8 bg-white rounded-lg shadow-xs dark:bg-gray-800">
    <div class="p-6">
        <h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
            Start New Import
        </h3>

        <!-- Marketplace Tabs -->
        {% call tabs_nav(tab_var='activeImportTab') %}
            {{ tab_button('letzshop', 'Letzshop', tab_var='activeImportTab', icon='shopping-cart', onclick="switchMarketplace('letzshop')") }}
            {{ tab_button('codeswholesale', 'CodesWholesale', tab_var='activeImportTab', icon='code', onclick="switchMarketplace('codeswholesale')") }}
        {% endcall %}

        <!-- Letzshop Import Form -->
        {{ tab_panel('letzshop', tab_var='activeImportTab') }}
        <form @submit.prevent="startImport()">
            <div class="grid gap-6 mb-4 md:grid-cols-2">
                <!-- Store Selection -->
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                        Store <span class="text-red-500">*</span>
                    </label>
                    <select
                        x-model="importForm.store_id"
                        @change="onStoreChange()"
                        required
                        class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none focus:shadow-outline-purple"
                    >
                        <option value="">Select a store...</option>
                        <template x-for="store in stores" :key="store.id">
                            <option :value="store.id" x-text="`${store.name} (${store.store_code})`"></option>
                        </template>
                    </select>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Select the store to import products for
                    </p>
                </div>

                <!-- CSV URL -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                        CSV URL <span class="text-red-500">*</span>
                    </label>
                    <input
                        x-model="importForm.csv_url"
                        type="url"
                        required
                        placeholder="https://example.com/products.csv"
                        class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none focus:shadow-outline-purple"
                    />
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Enter the URL of the Letzshop CSV feed
                    </p>
                </div>

                <!-- Language Selection -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                        Language
                    </label>
                    <select
                        x-model="importForm.language"
                        @change="onLanguageChange()"
                        class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none focus:shadow-outline-purple"
                    >
                        <option value="fr">French (FR)</option>
                        <option value="en">English (EN)</option>
                        <option value="de">German (DE)</option>
                    </select>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Select the language of the CSV feed
                    </p>
                </div>

                <!-- Batch Size -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                        Batch Size
                    </label>
                    {{ number_stepper(model='importForm.batch_size', min=100, max=5000, step=100, label='Batch Size') }}
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Number of products to process per batch (100-5000)
                    </p>
                </div>
            </div>

            <!-- Quick Fill Buttons (when store is selected) -->
            <div class="mb-4" x-show="importForm.store_id && selectedStore">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                    Quick Fill (from store settings)
                </label>
                <div class="flex flex-wrap gap-2">
                    <button
                        type="button"
                        @click="quickFill('fr')"
                        x-show="selectedStore?.letzshop_csv_url_fr"
                        class="flex items-center px-3 py-1 text-xs font-medium leading-5 text-purple-600 transition-colors duration-150 bg-purple-100 border border-purple-300 rounded-md hover:bg-purple-200 focus:outline-none"
                    >
                        <span x-html="$icon('lightning-bolt', 'w-3 h-3 mr-1')"></span>
                        French CSV
                    </button>
                    <button
                        type="button"
                        @click="quickFill('en')"
                        x-show="selectedStore?.letzshop_csv_url_en"
                        class="flex items-center px-3 py-1 text-xs font-medium leading-5 text-purple-600 transition-colors duration-150 bg-purple-100 border border-purple-300 rounded-md hover:bg-purple-200 focus:outline-none"
                    >
                        <span x-html="$icon('lightning-bolt', 'w-3 h-3 mr-1')"></span>
                        English CSV
                    </button>
                    <button
                        type="button"
                        @click="quickFill('de')"
                        x-show="selectedStore?.letzshop_csv_url_de"
                        class="flex items-center px-3 py-1 text-xs font-medium leading-5 text-purple-600 transition-colors duration-150 bg-purple-100 border border-purple-300 rounded-md hover:bg-purple-200 focus:outline-none"
                    >
                        <span x-html="$icon('lightning-bolt', 'w-3 h-3 mr-1')"></span>
                        German CSV
                    </button>
                </div>
                <p class="mt-1 text-xs text-red-600 dark:text-red-400" x-show="!selectedStore?.letzshop_csv_url_fr && !selectedStore?.letzshop_csv_url_en && !selectedStore?.letzshop_csv_url_de">
                    This store has no Letzshop CSV URLs configured
                </p>
            </div>

            <!-- Submit Button -->
            <div class="flex items-center justify-end">
                <button
                    type="submit"
                    :disabled="importing || !importForm.csv_url || !importForm.store_id"
                    class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:outline-none focus:shadow-outline-purple disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    <span x-show="!importing" x-html="$icon('upload', 'w-4 h-4 mr-2')"></span>
                    <span x-show="importing" x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
                    <span x-text="importing ? 'Starting Import...' : 'Start Import'"></span>
                </button>
            </div>
        </form>
        {{ endtab_panel() }}

        <!-- CodesWholesale Import Form -->
        {{ tab_panel('codeswholesale', tab_var='activeImportTab') }}
        <div class="text-center py-12">
            <span x-html="$icon('code', 'inline w-16 h-16 text-gray-300 dark:text-gray-600 mb-4')"></span>
            <h4 class="text-lg font-medium text-gray-700 dark:text-gray-300 mb-2">
                CodesWholesale Integration
            </h4>
            <p class="text-gray-500 dark:text-gray-400 mb-4">
                Import digital game keys and software licenses from CodesWholesale API.
            </p>
            <p class="text-sm text-gray-400 dark:text-gray-500">
                Coming soon - This feature is under development
            </p>
        </div>
        {{ endtab_panel() }}
    </div>
</div>

<!-- Filters -->
<div class="mb-4 bg-white rounded-lg shadow-xs dark:bg-gray-800 p-4">
    <div class="grid gap-4 md:grid-cols-4">
        <div>
            <label class="block text-xs font-medium text-gray-700 dark:text-gray-400 mb-1">
                Filter by Store
            </label>
            <select
                x-model="filters.store_id"
                @change="loadJobs()"
                class="block w-full px-2 py-1 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
            >
                <option value="">All Stores</option>
                <template x-for="store in stores" :key="store.id">
                    <option :value="store.id" x-text="`${store.name} (${store.store_code})`"></option>
                </template>
            </select>
        </div>

        <div>
            <label class="block text-xs font-medium text-gray-700 dark:text-gray-400 mb-1">
                Filter by Status
            </label>
            <select
                x-model="filters.status"
                @change="loadJobs()"
                class="block w-full px-2 py-1 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
            >
                <option value="">All Statuses</option>
                <option value="pending">Pending</option>
                <option value="processing">Processing</option>
                <option value="completed">Completed</option>
                <option value="failed">Failed</option>
                <option value="completed_with_errors">Completed with Errors</option>
            </select>
        </div>

        <div>
            <label class="block text-xs font-medium text-gray-700 dark:text-gray-400 mb-1">
                Filter by Marketplace
            </label>
            <select
                x-model="filters.marketplace"
                @change="loadJobs()"
                class="block w-full px-2 py-1 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
            >
                <option value="">All Marketplaces</option>
                <option value="Letzshop">Letzshop</option>
                <option value="CodesWholesale">CodesWholesale</option>
            </select>
        </div>

        <div class="flex items-end">
            <button
                @click="clearFilters()"
                class="px-3 py-1 text-sm font-medium leading-5 text-gray-700 dark:text-gray-300 transition-colors duration-150 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none"
            >
                Clear Filters
            </button>
        </div>
    </div>
</div>

<!-- Import Jobs List -->
<div class="bg-white rounded-lg shadow-xs dark:bg-gray-800">
    <div class="p-6">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                My Import Jobs
            </h3>
            <a href="/admin/imports" class="text-sm text-purple-600 hover:text-purple-700 dark:text-purple-400 dark:hover:text-purple-300">
                View all system imports →
            </a>
        </div>

        <!-- Loading State -->
        <div x-show="loading" class="text-center py-12">
            <span x-html="$icon('spinner', 'inline w-8 h-8 text-purple-600')"></span>
            <p class="mt-2 text-gray-600 dark:text-gray-400">Loading import jobs...</p>
        </div>

        <!-- Empty State -->
        <div x-show="!loading && jobs.length === 0" class="text-center py-12">
            <span x-html="$icon('inbox', 'inline w-12 h-12 text-gray-400 mb-4')"></span>
            <p class="text-gray-600 dark:text-gray-400">You haven't triggered any imports yet</p>
            <p class="text-sm text-gray-500 dark:text-gray-500">Start a new import using the form above</p>
        </div>

        <!-- Jobs Table -->
        <div x-show="!loading && jobs.length > 0">
            {% call table_wrapper() %}
                    {{ table_header(['Job ID', 'Store', 'Marketplace', 'Status', 'Progress', 'Started', 'Duration', 'Actions']) }}
                    <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                        <template x-for="job in jobs" :key="job.id">
                            <tr class="text-gray-700 dark:text-gray-400">
                                <td class="px-4 py-3 text-sm">
                                    #<span x-text="job.id"></span>
                                </td>
                                <td class="px-4 py-3 text-sm">
                                    <span x-text="getStoreName(job.store_id)"></span>
                                </td>
                                <td class="px-4 py-3 text-sm">
                                    <span x-text="job.marketplace"></span>
                                </td>
                                <td class="px-4 py-3 text-sm">
                                    <span class="px-2 py-1 font-semibold leading-tight rounded-full text-xs"
                                          :class="{
                                              'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100': job.status === 'completed',
                                              'text-blue-700 bg-blue-100 dark:bg-blue-700 dark:text-blue-100': job.status === 'processing',
                                              'text-yellow-700 bg-yellow-100 dark:bg-yellow-700 dark:text-yellow-100': job.status === 'pending',
                                              'text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100': job.status === 'failed',
                                              'text-orange-700 bg-orange-100 dark:bg-orange-700 dark:text-orange-100': job.status === 'completed_with_errors'
                                          }"
                                          x-text="job.status.replace('_', ' ').toUpperCase()">
                                    </span>
                                </td>
                                <td class="px-4 py-3 text-sm">
                                    <div class="space-y-1">
                                        <div class="text-xs text-gray-600 dark:text-gray-400">
                                            <span class="text-green-600 dark:text-green-400" x-text="job.imported_count"></span> imported,
                                            <span class="text-blue-600 dark:text-blue-400" x-text="job.updated_count"></span> updated
                                        </div>
                                        <div x-show="job.error_count > 0" class="text-xs text-red-600 dark:text-red-400">
                                            <span x-text="job.error_count"></span> errors
                                        </div>
                                        <div x-show="job.total_processed > 0" class="text-xs text-gray-500 dark:text-gray-500">
                                            Total: <span x-text="job.total_processed"></span>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 py-3 text-sm">
                                    <span x-text="job.started_at ? formatDate(job.started_at) : 'Not started'"></span>
                                </td>
                                <td class="px-4 py-3 text-sm">
                                    <span x-text="calculateDuration(job)"></span>
                                </td>
                                <td class="px-4 py-3 text-sm">
                                    <div class="flex items-center space-x-2">
                                        <button
                                            @click="viewJobDetails(job.id)"
                                            class="flex items-center justify-between px-2 py-1 text-xs font-medium leading-5 text-purple-600 rounded-lg dark:text-gray-400 focus:outline-none hover:bg-gray-100 dark:hover:bg-gray-700"
                                            title="View Details"
                                        >
                                            <span x-html="$icon('eye', 'w-4 h-4')"></span>
                                        </button>
                                        <button
                                            x-show="job.status === 'processing' || job.status === 'pending'"
                                            @click="refreshJobStatus(job.id)"
                                            class="flex items-center justify-between px-2 py-1 text-xs font-medium leading-5 text-blue-600 rounded-lg dark:text-gray-400 focus:outline-none hover:bg-gray-100 dark:hover:bg-gray-700"
                                            title="Refresh Status"
                                        >
                                            <span x-html="$icon('refresh', 'w-4 h-4')"></span>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </template>
                    </tbody>
        {% endcall %}

        {{ pagination(show_condition="!loading && pagination.total > 0") }}
    </div>
</div>

{{ job_details_modal() }}
{% endblock %}

{% block extra_scripts %}
<script defer src="{{ url_for('marketplace_static', path='admin/js/marketplace.js') }}?v=2"></script>
{% endblock %}
