{# app/templates/admin/letzshop.html #}
{% extends "admin/base.html" %}

{% from 'shared/macros/headers.html' import page_header_flex, refresh_button %}
{% from 'shared/macros/alerts.html' import error_state, alert_dynamic %}
{% from 'shared/macros/tables.html' import table_wrapper, table_header %}
{% from 'shared/macros/modals.html' import modal, confirm_modal %}

{% block title %}Letzshop Management{% endblock %}

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

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

{% block content %}
<!-- Page Header -->
{% call page_header_flex(title='Letzshop Management', subtitle='Manage Letzshop integration for all stores') %}
    {{ refresh_button(loading_var='loading', onclick='refreshData()') }}
{% endcall %}

<!-- Success Message -->
{{ alert_dynamic(type='success', title='', message_var='successMessage', show_condition='successMessage') }}

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

<!-- Summary Cards -->
<div class="grid gap-6 mb-8 md:grid-cols-4">
    <!-- Total Stores -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:bg-purple-900">
            <span x-html="$icon('office-building', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Total Stores</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.total"></p>
        </div>
    </div>

    <!-- Configured -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:bg-green-900">
            <span x-html="$icon('check-circle', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Configured</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.configured"></p>
        </div>
    </div>

    <!-- Auto-Sync Enabled -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:bg-blue-900">
            <span x-html="$icon('refresh', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Auto-Sync</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.autoSync"></p>
        </div>
    </div>

    <!-- Pending Orders -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:bg-orange-900">
            <span x-html="$icon('clock', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Pending Orders</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.pendingOrders"></p>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="mb-4 flex flex-wrap gap-4">
    <label class="flex items-center">
        <input
            type="checkbox"
            x-model="filters.configuredOnly"
            @change="loadStores()"
            class="form-checkbox h-4 w-4 text-purple-600 rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700"
        />
        <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Configured only</span>
    </label>
</div>

<!-- Stores Table -->
{% call table_wrapper() %}
    {{ table_header(['Store', 'Status', 'Auto-Sync', 'Last Sync', 'Orders', 'Actions']) }}
    <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
        <template x-if="loading && stores.length === 0">
            <tr>
                <td colspan="6" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                    <span x-html="$icon('spinner', 'w-6 h-6 mx-auto mb-2')"></span>
                    <p>Loading stores...</p>
                </td>
            </tr>
        </template>
        <template x-if="!loading && stores.length === 0">
            <tr>
                <td colspan="6" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                    <span x-html="$icon('office-building', 'w-12 h-12 mx-auto mb-2 text-gray-300')"></span>
                    <p class="font-medium">No stores found</p>
                </td>
            </tr>
        </template>
        <template x-for="store in stores" :key="store.store_id">
            <tr class="text-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700">
                <td class="px-4 py-3">
                    <div class="flex items-center text-sm">
                        <div class="relative hidden w-8 h-8 mr-3 rounded-full md:block">
                            <div class="absolute inset-0 rounded-full bg-purple-100 dark:bg-purple-900 flex items-center justify-center">
                                <span class="text-sm font-semibold text-purple-600 dark:text-purple-300" x-text="store.store_name.charAt(0).toUpperCase()"></span>
                            </div>
                        </div>
                        <div>
                            <p class="font-semibold" x-text="store.store_name"></p>
                            <p class="text-xs text-gray-500" x-text="store.store_code"></p>
                        </div>
                    </div>
                </td>
                <td class="px-4 py-3 text-xs">
                    <span
                        class="px-2 py-1 font-semibold leading-tight rounded-full"
                        :class="store.is_configured ? 'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100' : 'text-gray-700 bg-gray-100 dark:bg-gray-600 dark:text-gray-100'"
                        x-text="store.is_configured ? 'CONFIGURED' : 'NOT CONFIGURED'"
                    ></span>
                </td>
                <td class="px-4 py-3 text-sm">
                    <span x-show="store.auto_sync_enabled" class="text-green-600 dark:text-green-400">
                        <span x-html="$icon('check', 'w-4 h-4 inline')"></span> Enabled
                    </span>
                    <span x-show="!store.auto_sync_enabled" class="text-gray-400">
                        <span x-html="$icon('x', 'w-4 h-4 inline')"></span> Disabled
                    </span>
                </td>
                <td class="px-4 py-3 text-sm">
                    <div x-show="store.last_sync_at">
                        <span
                            class="px-2 py-0.5 text-xs rounded-full"
                            :class="{
                                'bg-green-100 text-green-700': store.last_sync_status === 'success',
                                'bg-yellow-100 text-yellow-700': store.last_sync_status === 'partial',
                                'bg-red-100 text-red-700': store.last_sync_status === 'failed'
                            }"
                            x-text="store.last_sync_status"
                        ></span>
                        <p class="text-xs text-gray-500 mt-1" x-text="formatDate(store.last_sync_at)"></p>
                    </div>
                    <span x-show="!store.last_sync_at" class="text-gray-400">Never</span>
                </td>
                <td class="px-4 py-3 text-sm">
                    <div class="flex items-center gap-2">
                        <span
                            class="px-2 py-0.5 text-xs rounded-full bg-orange-100 text-orange-700"
                            x-show="store.pending_orders > 0"
                            x-text="store.pending_orders + ' pending'"
                        ></span>
                        <span class="text-gray-500" x-text="store.total_orders + ' total'"></span>
                    </div>
                </td>
                <td class="px-4 py-3">
                    <div class="flex items-center space-x-2 text-sm">
                        <button
                            @click="openConfigModal(store)"
                            class="flex items-center justify-center px-2 py-1 text-sm text-purple-600 transition-colors duration-150 rounded-md hover:bg-purple-100 dark:hover:bg-purple-900"
                            title="Configure"
                        >
                            <span x-html="$icon('cog', 'w-4 h-4')"></span>
                        </button>
                        <button
                            x-show="store.is_configured"
                            @click="testConnection(store)"
                            class="flex items-center justify-center px-2 py-1 text-sm text-blue-600 transition-colors duration-150 rounded-md hover:bg-blue-100 dark:hover:bg-blue-900"
                            title="Test Connection"
                        >
                            <span x-html="$icon('lightning-bolt', 'w-4 h-4')"></span>
                        </button>
                        <button
                            x-show="store.is_configured"
                            @click="triggerSync(store)"
                            class="flex items-center justify-center px-2 py-1 text-sm text-green-600 transition-colors duration-150 rounded-md hover:bg-green-100 dark:hover:bg-green-900"
                            title="Trigger Sync"
                        >
                            <span x-html="$icon('download', 'w-4 h-4')"></span>
                        </button>
                        <button
                            x-show="store.total_orders > 0"
                            @click="viewOrders(store)"
                            class="flex items-center justify-center px-2 py-1 text-sm text-gray-600 transition-colors duration-150 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700"
                            title="View Orders"
                        >
                            <span x-html="$icon('eye', 'w-4 h-4')"></span>
                        </button>
                    </div>
                </td>
            </tr>
        </template>
    </tbody>
{% endcall %}

<!-- Pagination -->
<div x-show="totalStores > limit" class="mt-4 grid px-4 py-3 text-xs font-semibold tracking-wide text-gray-500 uppercase border dark:border-gray-700 rounded-lg bg-gray-50 sm:grid-cols-9 dark:text-gray-400 dark:bg-gray-800">
    <span class="flex items-center col-span-3">
        Showing <span x-text="((page - 1) * limit) + 1"></span>-<span x-text="Math.min(page * limit, totalStores)"></span> of <span x-text="totalStores"></span>
    </span>
    <span class="col-span-2"></span>
    <span class="flex col-span-4 mt-2 sm:mt-auto sm:justify-end">
        <nav>
            <ul class="inline-flex items-center">
                <li>
                    <button @click="page--; loadStores()" :disabled="page <= 1" class="px-3 py-1 rounded-md disabled:opacity-50">
                        <span x-html="$icon('chevron-left', 'w-4 h-4')"></span>
                    </button>
                </li>
                <li>
                    <button @click="page++; loadStores()" :disabled="page * limit >= totalStores" class="px-3 py-1 rounded-md disabled:opacity-50">
                        <span x-html="$icon('chevron-right', 'w-4 h-4')"></span>
                    </button>
                </li>
            </ul>
        </nav>
    </span>
</div>

<!-- Configuration Modal -->
{% call modal('configModal', 'Configure Letzshop', 'showConfigModal', size='md') %}
    <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
        Configuring: <span class="font-semibold" x-text="selectedStore?.store_name"></span>
    </p>
    <form @submit.prevent="saveStoreConfig()">
        <div class="space-y-4 mb-6">
            <!-- API Key -->
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                    API Key <span x-show="!storeCredentials" class="text-red-500">*</span>
                </label>
                <div class="relative">
                    <input
                        :type="showApiKey ? 'text' : 'password'"
                        x-model="configForm.api_key"
                        :placeholder="storeCredentials ? storeCredentials.api_key_masked : 'Enter API key'"
                        class="block w-full px-3 py-2 pr-10 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"
                    />
                    <button type="button" @click="showApiKey = !showApiKey" class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400">
                        <span x-html="$icon(showApiKey ? 'eye-off' : 'eye', 'w-4 h-4')"></span>
                    </button>
                </div>
            </div>

            <!-- Auto Sync -->
            <div>
                <label class="flex items-center cursor-pointer">
                    <input
                        type="checkbox"
                        x-model="configForm.auto_sync_enabled"
                        class="form-checkbox h-5 w-5 text-purple-600 rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                    />
                    <span class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-400">Enable Auto-Sync</span>
                </label>
            </div>

            <!-- Sync Interval -->
            <div x-show="configForm.auto_sync_enabled">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                    Sync Interval
                </label>
                <select
                    x-model="configForm.sync_interval_minutes"
                    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"
                >
                    <option value="15">Every 15 minutes</option>
                    <option value="30">Every 30 minutes</option>
                    <option value="60">Every hour</option>
                    <option value="120">Every 2 hours</option>
                </select>
            </div>
        </div>

        <div class="flex justify-between">
            <button
                type="button"
                x-show="storeCredentials"
                @click="showDeleteStoreConfigModal = true"
                class="px-4 py-2 text-sm font-medium text-red-600 border border-red-300 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20"
            >
                Remove
            </button>
            <div class="flex gap-3 ml-auto">
                <button
                    type="button"
                    @click="showConfigModal = false"
                    class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50"
                >
                    Cancel
                </button>
                <button
                    type="submit"
                    :disabled="savingConfig"
                    class="flex items-center px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50"
                >
                    <span x-show="savingConfig" x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
                    <span x-text="savingConfig ? 'Saving...' : 'Save'"></span>
                </button>
            </div>
        </div>
    </form>
{% endcall %}

<!-- Orders Modal -->
<!-- Delete Store Config Confirm Modal -->
{{ confirm_modal('deleteStoreConfigModal', 'Remove Configuration', 'Are you sure you want to remove the Letzshop configuration for this store? This will delete the API key and disable syncing.', 'deleteStoreConfig()', 'showDeleteStoreConfigModal', 'Remove', 'Cancel', 'danger') }}

{% call modal('ordersModal', 'Store Orders', 'showOrdersModal', size='xl') %}
    <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
        Orders for: <span class="font-semibold" x-text="selectedStore?.store_name"></span>
    </p>

    <div x-show="loadingOrders" class="py-8 text-center">
        <span x-html="$icon('spinner', 'w-6 h-6 mx-auto')"></span>
    </div>

    <div x-show="!loadingOrders">
        <table class="w-full text-sm">
            <thead>
                <tr class="text-left text-gray-500 border-b dark:border-gray-700">
                    <th class="pb-2">Order</th>
                    <th class="pb-2">Customer</th>
                    <th class="pb-2">Total</th>
                    <th class="pb-2">Status</th>
                    <th class="pb-2">Date</th>
                </tr>
            </thead>
            <tbody class="divide-y dark:divide-gray-700">
                <template x-for="order in storeOrders" :key="order.id">
                    <tr class="text-gray-700 dark:text-gray-400">
                        <td class="py-2" x-text="order.letzshop_order_number || order.letzshop_order_id"></td>
                        <td class="py-2" x-text="order.customer_email || 'N/A'"></td>
                        <td class="py-2" x-text="order.total_amount ? order.total_amount + ' ' + order.currency : 'N/A'"></td>
                        <td class="py-2">
                            <span
                                class="px-2 py-0.5 text-xs rounded-full"
                                :class="{
                                    'bg-orange-100 text-orange-700': order.sync_status === 'pending',
                                    'bg-green-100 text-green-700': order.sync_status === 'confirmed',
                                    'bg-red-100 text-red-700': order.sync_status === 'rejected',
                                    'bg-blue-100 text-blue-700': order.sync_status === 'shipped'
                                }"
                                x-text="order.sync_status"
                            ></span>
                        </td>
                        <td class="py-2" x-text="formatDate(order.created_at)"></td>
                    </tr>
                </template>
            </tbody>
        </table>
        <p x-show="storeOrders.length === 0" class="py-4 text-center text-gray-500">No orders found</p>
    </div>
{% endcall %}
{% endblock %}
