{# app/templates/store/marketplace.html #}
{% extends "store/base.html" %}
{% from 'shared/macros/inputs.html' import number_stepper %}
{% from 'shared/macros/headers.html' import page_header_flex, refresh_button %}
{% from 'shared/macros/alerts.html' import error_state %}
{% from 'shared/macros/tables.html' import table_wrapper, table_header, simple_pagination %}
{% from 'shared/macros/modals.html' import job_details_modal %}

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

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

{% block extra_scripts %}
<script defer src="/static/modules/marketplace/store/js/marketplace.js"></script>
{% endblock %}

{% block content %}
<!-- Page Header -->
{% call page_header_flex(title='Marketplace Import', subtitle='Import products from Letzshop marketplace CSV feeds') %}
    {{ refresh_button(loading_var='loading', onclick='refreshJobs()') }}
{% endcall %}

<!-- Success Message -->
<div x-show="successMessage" x-transition class="mb-6 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-start">
    <span x-html="$icon('check-circle', 'w-5 h-5 mr-3 mt-0.5 flex-shrink-0')"></span>
    <div>
        <p class="font-semibold" x-text="successMessage"></p>
    </div>
</div>

<!-- Error Message -->
{{ error_state(title='Error', error_var='error', show_condition='error') }}

<!-- Import Form Card -->
<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>

        <form @submit.prevent="startImport()">
            <div class="grid gap-6 mb-4 md:grid-cols-2">
                <!-- 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"
                        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>

                <!-- Marketplace -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                        Marketplace
                    </label>
                    <input
                        x-model="importForm.marketplace"
                        type="text"
                        readonly
                        class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-600 border border-gray-300 dark:border-gray-600 rounded-md cursor-not-allowed"
                    />
                </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 -->
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                    Quick Fill
                </label>
                <div class="flex flex-wrap gap-2">
                    <button
                        type="button"
                        @click="quickFill('fr')"
                        x-show="storeSettings.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="storeSettings.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="storeSettings.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-gray-500 dark:text-gray-400" x-show="!storeSettings.letzshop_csv_url_fr && !storeSettings.letzshop_csv_url_en && !storeSettings.letzshop_csv_url_de">
                    Configure Letzshop CSV URLs in settings to use quick fill
                </p>
            </div>

            <!-- Submit Button -->
            <div class="flex items-center justify-end">
                <button
                    type="submit"
                    :disabled="importing || !importForm.csv_url"
                    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>
    </div>
</div>

<!-- Import Jobs List -->
<div class="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">
            Import History
        </h3>

        <!-- 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">No import jobs yet</p>
            <p class="text-sm text-gray-500 dark:text-gray-500">Start your first import using the form above</p>
        </div>

        <!-- Jobs Table -->
        <div x-show="!loading && jobs.length > 0">
            {% call table_wrapper() %}
                {{ table_header(['Job ID', '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="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 %}
        </div>

        <!-- Pagination -->
        {# noqa: FE-001 - Custom pagination with text buttons and totalJobs variable #}
        <div x-show="!loading && totalJobs > limit" class="px-4 py-3 border-t dark:border-gray-700">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-700 dark:text-gray-400">
                    Showing <span x-text="((page - 1) * limit) + 1"></span> to
                    <span x-text="Math.min(page * limit, totalJobs)"></span> of
                    <span x-text="totalJobs"></span> jobs
                </div>
                <div class="flex space-x-2">
                    <button
                        @click="previousPage()"
                        :disabled="page === 1"
                        class="px-3 py-1 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-md hover:bg-purple-700 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        Previous
                    </button>
                    <button
                        @click="nextPage()"
                        :disabled="page * limit >= totalJobs"
                        class="px-3 py-1 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-md hover:bg-purple-700 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        Next
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

{# noqa: FE-004 - Custom modal with different field names (imported_count vs imported) #}
<!-- Job Details Modal -->
<div x-show="showJobModal"
     x-cloak
     @click.away="closeJobModal()"
     class="fixed inset-0 z-30 flex items-end bg-black bg-opacity-50 sm:items-center sm:justify-center"
     x-transition:enter="transition ease-out duration-150"
     x-transition:enter-start="opacity-0"
     x-transition:enter-end="opacity-100"
     x-transition:leave="transition ease-in duration-150"
     x-transition:leave-start="opacity-100"
     x-transition:leave-end="opacity-0">
    <div @click.away="closeJobModal()"
         class="w-full px-6 py-4 overflow-hidden bg-white rounded-t-lg dark:bg-gray-800 sm:rounded-lg sm:m-4 sm:max-w-2xl"
         x-transition:enter="transition ease-out duration-150"
         x-transition:enter-start="opacity-0 transform translate-y-1/2"
         x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-150"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0 transform translate-y-1/2">
        <!-- Modal Header -->
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                Import Job Details
            </h3>
            <button @click="closeJobModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                <span x-html="$icon('close', 'w-5 h-5')"></span>
            </button>
        </div>

        <!-- Modal Content -->
        <div x-show="selectedJob" class="space-y-4">
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Job ID</p>
                    <p class="text-sm text-gray-900 dark:text-gray-100" x-text="selectedJob?.id"></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Marketplace</p>
                    <p class="text-sm text-gray-900 dark:text-gray-100" x-text="selectedJob?.marketplace"></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Status</p>
                    <span class="px-2 py-1 font-semibold leading-tight rounded-full text-xs"
                          :class="{
                              'text-green-700 bg-green-100': selectedJob?.status === 'completed',
                              'text-blue-700 bg-blue-100': selectedJob?.status === 'processing',
                              'text-yellow-700 bg-yellow-100': selectedJob?.status === 'pending',
                              'text-red-700 bg-red-100': selectedJob?.status === 'failed',
                              'text-orange-700 bg-orange-100': selectedJob?.status === 'completed_with_errors'
                          }"
                          x-text="selectedJob?.status.replace('_', ' ').toUpperCase()">
                    </span>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Source URL</p>
                    <p class="text-sm text-gray-900 dark:text-gray-100 truncate" x-text="selectedJob?.source_url" :title="selectedJob?.source_url"></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Imported</p>
                    <p class="text-sm text-green-600 dark:text-green-400" x-text="selectedJob?.imported_count"></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Updated</p>
                    <p class="text-sm text-blue-600 dark:text-blue-400" x-text="selectedJob?.updated_count"></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Errors</p>
                    <p class="text-sm text-red-600 dark:text-red-400" x-text="selectedJob?.error_count"></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Total Processed</p>
                    <p class="text-sm text-gray-900 dark:text-gray-100" x-text="selectedJob?.total_processed"></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Started At</p>
                    <p class="text-sm text-gray-900 dark:text-gray-100" x-text="selectedJob?.started_at ? formatDate(selectedJob.started_at) : 'Not started'"></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Completed At</p>
                    <p class="text-sm text-gray-900 dark:text-gray-100" x-text="selectedJob?.completed_at ? formatDate(selectedJob.completed_at) : 'Not completed'"></p>
                </div>
            </div>

            <!-- Error Details -->
            <div x-show="selectedJob?.error_details?.length > 0" class="mt-4">
                <p class="text-sm font-medium text-gray-600 dark:text-gray-400 mb-2">Error Details</p>
                <div class="p-3 bg-red-50 dark:bg-red-900/20 rounded-lg max-h-48 overflow-y-auto">
                    <pre class="text-xs text-red-700 dark:text-red-300 whitespace-pre-wrap" x-text="JSON.stringify(selectedJob?.error_details, null, 2)"></pre>
                </div>
            </div>
        </div>

        <!-- Modal Footer -->
        <div class="flex justify-end mt-6">
            <button
                @click="closeJobModal()"
                class="px-4 py-2 text-sm font-medium leading-5 text-gray-700 transition-colors duration-150 border border-gray-300 rounded-lg dark:text-gray-400 dark:border-gray-700 hover:border-gray-500 focus:outline-none"
            >
                Close
            </button>
        </div>
    </div>
</div>
{% endblock %}
