{# app/templates/admin/subscription-tiers.html #}
{# noqa: FE-008 - Using raw number inputs for cents/limits in admin tier config modal #}
{% extends "admin/base.html" %}
{% from 'shared/macros/alerts.html' import alert_dynamic, error_state %}
{% from 'shared/macros/headers.html' import page_header_refresh %}
{% from 'shared/macros/tables.html' import table_wrapper, table_header_custom, th_sortable %}
{% from 'shared/macros/modals.html' import modal_confirm %}

{% block title %}Subscription Tiers{% endblock %}

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

{% block content %}
{{ page_header_refresh('Subscription Tiers') }}

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

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

<!-- Stats Cards -->
<div class="grid gap-6 mb-8 md:grid-cols-4">
    <!-- Total Tiers -->
    <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:text-purple-100 dark:bg-purple-500">
            <span x-html="$icon('tag', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Total Tiers</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="tiers.length">0</p>
        </div>
    </div>

    <!-- Active Tiers -->
    <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:text-green-100 dark:bg-green-500">
            <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">Active Tiers</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="tiers.filter(t => t.is_active).length">0</p>
        </div>
    </div>

    <!-- Public Tiers -->
    <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:text-blue-100 dark:bg-blue-500">
            <span x-html="$icon('eye', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Public Tiers</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="tiers.filter(t => t.is_public).length">0</p>
        </div>
    </div>

    <!-- MRR -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-yellow-500 bg-yellow-100 rounded-full dark:text-yellow-100 dark:bg-yellow-500">
            <span x-html="$icon('currency-euro', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Est. MRR</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats ? formatCurrency(stats.mrr_cents) : '-'">-</p>
        </div>
    </div>
</div>

<!-- Filters & Actions -->
<div class="mb-4 flex flex-wrap items-center justify-between gap-4">
    <div class="flex items-center gap-4">
        <label class="flex items-center text-sm text-gray-600 dark:text-gray-400">
            <input type="checkbox" x-model="includeInactive" @change="loadTiers()" class="mr-2 rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700">
            Show inactive tiers
        </label>
        <select x-model="filterPlatformId" @change="loadTiers()"
                class="px-3 py-1.5 text-sm border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300">
            <option value="">All Platforms</option>
            <template x-for="p in platforms" :key="p.id">
                <option :value="p.id" x-text="p.name"></option>
            </template>
        </select>
    </div>

    <button
        @click="openCreateModal()"
        class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500"
    >
        <span x-html="$icon('plus', 'w-4 h-4 mr-2')"></span>
        Create Tier
    </button>
</div>

<!-- Tiers Table -->
{% call table_wrapper() %}
    <table class="w-full whitespace-nowrap">
        {% call table_header_custom() %}
            <th class="px-4 py-3">#</th>
            <th class="px-4 py-3">Platform</th>
            {{ th_sortable('code', 'Code', 'sortBy', 'sortOrder') }}
            {{ th_sortable('name', 'Name', 'sortBy', 'sortOrder') }}
            <th class="px-4 py-3 text-right">Monthly</th>
            <th class="px-4 py-3 text-right">Annual</th>
            <th class="px-4 py-3 text-center">Features</th>
            <th class="px-4 py-3 text-center">Status</th>
            <th class="px-4 py-3 text-right">Actions</th>
        {% endcall %}
        <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
            <template x-if="loading">
                <tr>
                    <td colspan="9" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                        <span x-html="$icon('refresh', 'inline w-6 h-6 animate-spin mr-2')"></span>
                        Loading tiers...
                    </td>
                </tr>
            </template>
            <template x-if="!loading && tiers.length === 0">
                <tr>
                    <td colspan="9" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                        No subscription tiers found.
                    </td>
                </tr>
            </template>
            <template x-for="(tier, index) in tiers" :key="tier.id">
                <tr class="text-gray-700 dark:text-gray-400" :class="{ 'opacity-50': !tier.is_active }">
                    <td class="px-4 py-3 text-sm" x-text="tier.display_order"></td>
                    <td class="px-4 py-3 text-sm" x-text="tier.platform_name || 'Global'"></td>
                    <td class="px-4 py-3">
                        <span class="px-2 py-1 text-xs font-medium rounded-full"
                              :class="{
                                  'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200': tier.code === 'essential',
                                  'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200': tier.code === 'professional',
                                  'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200': tier.code === 'business',
                                  'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200': tier.code === 'enterprise',
                                  'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200': !['essential','professional','business','enterprise'].includes(tier.code)
                              }"
                              x-text="tier.code.toUpperCase()"></span>
                    </td>
                    <td class="px-4 py-3 text-sm font-medium text-gray-900 dark:text-gray-100" x-text="tier.name"></td>
                    <td class="px-4 py-3 text-sm text-right font-mono" x-text="formatCurrency(tier.price_monthly_cents)"></td>
                    <td class="px-4 py-3 text-sm text-right font-mono" x-text="tier.price_annual_cents ? formatCurrency(tier.price_annual_cents) : '-'"></td>
                    <td class="px-4 py-3 text-sm text-center">
                        <span class="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 rounded" x-text="(tier.feature_codes || tier.features || []).length"></span>
                    </td>
                    <td class="px-4 py-3 text-center">
                        <span x-show="tier.is_active && tier.is_public" class="px-2 py-1 text-xs font-medium text-green-700 bg-green-100 rounded-full dark:bg-green-900 dark:text-green-200">Active</span>
                        <span x-show="tier.is_active && !tier.is_public" class="px-2 py-1 text-xs font-medium text-blue-700 bg-blue-100 rounded-full dark:bg-blue-900 dark:text-blue-200">Private</span>
                        <span x-show="!tier.is_active" class="px-2 py-1 text-xs font-medium text-gray-700 bg-gray-100 rounded-full dark:bg-gray-700 dark:text-gray-300">Inactive</span>
                    </td>
                    <td class="px-4 py-3 text-right">
                        <div class="flex items-center justify-end gap-2">
                            <button @click="openFeaturePanel(tier)" class="p-2 text-gray-500 hover:text-blue-600 dark:hover:text-blue-400" title="Edit Features">
                                <span x-html="$icon('puzzle-piece', 'w-4 h-4')"></span>
                            </button>
                            <button @click="openEditModal(tier)" class="p-2 text-gray-500 hover:text-purple-600 dark:hover:text-purple-400" title="Edit">
                                <span x-html="$icon('pencil', 'w-4 h-4')"></span>
                            </button>
                            <button
                                x-show="!tier.is_active"
                                @click="toggleTierStatus(tier, true)"
                                class="p-2 text-gray-500 hover:text-green-600 dark:hover:text-green-400"
                                title="Activate"
                            >
                                <span x-html="$icon('check-circle', 'w-4 h-4')"></span>
                            </button>
                            <button
                                x-show="tier.is_active"
                                @click="toggleTierStatus(tier, false)"
                                class="p-2 text-gray-500 hover:text-red-600 dark:hover:text-red-400"
                                title="Deactivate"
                            >
                                <span x-html="$icon('x-circle', 'w-4 h-4')"></span>
                            </button>
                        </div>
                    </td>
                </tr>
            </template>
        </tbody>
    </table>
{% endcall %}

<!-- Create/Edit Modal -->
<div x-show="showModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center overflow-auto bg-black bg-opacity-50">
    <div class="relative w-full max-w-2xl p-6 mx-4 bg-white rounded-lg shadow-xl dark:bg-gray-800" @click.away="closeModal()">
        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4" x-text="editingTier ? 'Edit Tier' : 'Create Tier'"></h3>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <!-- Code -->
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Code</label>
                <input
                    type="text"
                    x-model="formData.code"
                    :disabled="editingTier"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-white disabled:opacity-50"
                    placeholder="e.g., premium"
                >
            </div>

            <!-- Platform -->
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Platform</label>
                <select
                    x-model="formData.platform_id"
                    :disabled="editingTier"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-white disabled:opacity-50"
                >
                    <option :value="null">Global (all platforms)</option>
                    <template x-for="p in platforms" :key="p.id">
                        <option :value="p.id" x-text="p.name"></option>
                    </template>
                </select>
            </div>

            <!-- Name -->
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name</label>
                <input
                    type="text"
                    x-model="formData.name"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                    placeholder="e.g., Premium Plan"
                >
            </div>

            <!-- Monthly Price -->
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Monthly Price (cents)</label>
                <input
                    type="number"
                    x-model.number="formData.price_monthly_cents"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                    placeholder="e.g., 4900 for 49.00"
                >
            </div>

            <!-- Annual Price -->
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Annual Price (cents)</label>
                <input
                    type="number"
                    x-model.number="formData.price_annual_cents"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                    placeholder="e.g., 49000 for 490.00"
                >
            </div>

            <!-- Display Order -->
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Display Order</label>
                <input
                    type="number"
                    x-model.number="formData.display_order"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                    placeholder="e.g., 1"
                >
            </div>

            <!-- Stripe Product ID -->
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Stripe Product ID</label>
                <input
                    type="text"
                    x-model="formData.stripe_product_id"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                    placeholder="prod_..."
                >
            </div>

            <!-- Stripe Monthly Price ID -->
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Stripe Monthly Price ID</label>
                <input
                    type="text"
                    x-model="formData.stripe_price_monthly_id"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                    placeholder="price_..."
                >
            </div>

            <!-- Description -->
            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Description</label>
                <textarea
                    x-model="formData.description"
                    rows="2"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                    placeholder="Brief description of this tier..."
                ></textarea>
            </div>

            <!-- Toggles -->
            <div class="md:col-span-2 flex gap-6">
                <label class="flex items-center">
                    <input type="checkbox" x-model="formData.is_active" class="mr-2 rounded border-gray-300 dark:border-gray-600">
                    <span class="text-sm text-gray-700 dark:text-gray-300">Active</span>
                </label>
                <label class="flex items-center">
                    <input type="checkbox" x-model="formData.is_public" class="mr-2 rounded border-gray-300 dark:border-gray-600">
                    <span class="text-sm text-gray-700 dark:text-gray-300">Public (visible to stores)</span>
                </label>
            </div>
        </div>

        <!-- Modal Actions -->
        <div class="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
            <button
                @click="closeModal()"
                class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600"
            >
                Cancel
            </button>
            <button
                @click="saveTier()"
                :disabled="saving"
                class="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="!saving" x-text="editingTier ? 'Update' : 'Create'"></span>
                <span x-show="saving">Saving...</span>
            </button>
        </div>
    </div>
</div>

<!-- Feature Assignment Slide-over Panel -->
<div
    x-show="showFeaturePanel"
    x-cloak
    @keydown.escape.window="closeFeaturePanel()"
    class="fixed inset-0 z-50 overflow-hidden"
    role="dialog"
    aria-modal="true"
>
    <!-- Backdrop -->
    <div
        x-show="showFeaturePanel"
        x-transition:enter="ease-out duration-300"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        x-transition:leave="ease-in duration-200"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        class="fixed inset-0 bg-gray-500/50 dark:bg-gray-900/80 backdrop-blur-sm"
        @click="closeFeaturePanel()"
    ></div>

    <!-- Panel -->
    <div class="fixed inset-y-0 right-0 flex max-w-full pl-10">
        <div
            x-show="showFeaturePanel"
            x-transition:enter="transform transition ease-in-out duration-300"
            x-transition:enter-start="translate-x-full"
            x-transition:enter-end="translate-x-0"
            x-transition:leave="transform transition ease-in-out duration-300"
            x-transition:leave-start="translate-x-0"
            x-transition:leave-end="translate-x-full"
            class="w-screen max-w-lg h-full"
        >
            <div class="flex h-full flex-col bg-white dark:bg-gray-800 shadow-xl">
                <!-- Header -->
                <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                    <div>
                        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Edit Features</h2>
                        <p class="text-sm text-gray-500 dark:text-gray-400" x-text="selectedTierForFeatures?.name"></p>
                    </div>
                    <button
                        @click="closeFeaturePanel()"
                        class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                    >
                        <span x-html="$icon('x', 'w-5 h-5')"></span>
                    </button>
                </div>

                <!-- Body -->
                <div class="flex-1 overflow-y-auto px-6 py-4">
                    <!-- Loading State -->
                    <div x-show="loadingFeatures" class="flex items-center justify-center py-8">
                        <span x-html="$icon('refresh', 'w-6 h-6 animate-spin text-purple-600')"></span>
                        <span class="ml-2 text-gray-500 dark:text-gray-400">Loading features...</span>
                    </div>

                    <!-- Feature Categories -->
                    <div x-show="!loadingFeatures" class="space-y-6">
                        <template x-for="category in categories" :key="category">
                            <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                                <!-- Category Header -->
                                <div class="flex items-center justify-between px-4 py-3 bg-gray-50 dark:bg-gray-700/50">
                                    <h3 class="text-sm font-medium text-gray-900 dark:text-white" x-text="formatCategoryName(category)"></h3>
                                    <div class="flex items-center gap-2">
                                        <button
                                            @click="selectAllInCategory(category)"
                                            class="text-xs text-purple-600 dark:text-purple-400 hover:underline"
                                            x-show="!allSelectedInCategory(category)"
                                        >
                                            Select all
                                        </button>
                                        <button
                                            @click="deselectAllInCategory(category)"
                                            class="text-xs text-gray-500 dark:text-gray-400 hover:underline"
                                            x-show="allSelectedInCategory(category)"
                                        >
                                            Deselect all
                                        </button>
                                    </div>
                                </div>

                                <!-- Features List -->
                                <div class="divide-y divide-gray-100 dark:divide-gray-700">
                                    <template x-for="feature in featuresGrouped[category]" :key="feature.code">
                                        <div class="flex items-start px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-700/30">
                                            <label class="flex items-start cursor-pointer flex-1">
                                                <input
                                                    type="checkbox"
                                                    :checked="isFeatureSelected(feature.code)"
                                                    @change="toggleFeature(feature.code)"
                                                    class="mt-0.5 rounded border-gray-300 dark:border-gray-600 text-purple-600 focus:ring-purple-500"
                                                >
                                                <div class="ml-3">
                                                    <div class="text-sm font-medium text-gray-900 dark:text-white" x-text="feature.name_key || feature.name"></div>
                                                    <div class="text-xs text-gray-500 dark:text-gray-400" x-text="feature.description_key || feature.description"></div>
                                                </div>
                                            </label>
                                            <template x-if="feature.feature_type === 'quantitative' && isFeatureSelected(feature.code)">
                                                <div class="ml-2 flex-shrink-0">
                                                    <input
                                                        type="number"
                                                        :value="getFeatureLimitValue(feature.code)"
                                                        @input="setFeatureLimitValue(feature.code, $event.target.value)"
                                                        placeholder="Unlimited"
                                                        class="w-24 px-2 py-1 text-sm border border-gray-300 rounded dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                                                        min="0"
                                                    >
                                                </div>
                                            </template>
                                        </div>
                                    </template>
                                </div>
                            </div>
                        </template>

                        <!-- Empty State -->
                        <div x-show="categories.length === 0" class="text-center py-8 text-gray-500 dark:text-gray-400">
                            No features available.
                        </div>
                    </div>
                </div>

                <!-- Footer -->
                <div class="flex items-center justify-between px-6 py-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                        <span x-text="selectedFeatures.length"></span> features selected
                    </div>
                    <div class="flex items-center gap-3">
                        <button
                            @click="closeFeaturePanel()"
                            type="button"
                            class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
                        >
                            Cancel
                        </button>
                        <button
                            @click="saveFeatures()"
                            :disabled="savingFeatures"
                            class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 disabled:opacity-50"
                        >
                            <span x-show="savingFeatures" x-html="$icon('refresh', 'w-4 h-4 mr-2 animate-spin')"></span>
                            <span x-text="savingFeatures ? 'Saving...' : 'Save Features'"></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_scripts %}
<script defer src="{{ url_for('billing_static', path='admin/js/subscription-tiers.js') }}"></script>
{% endblock %}
