{% extends "admin/base.html" %}

{% block title %}Feature Management{% endblock %}

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

{% block content %}
<div class="py-6">
    <!-- Header -->
    <div class="mb-8">
        <h2 class="text-2xl font-semibold text-gray-700 dark:text-gray-200">
            Feature Management
        </h2>
        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
            Configure which features are available to each subscription tier.
        </p>
    </div>

    <!-- Loading State -->
    <div x-show="loading" class="flex justify-center py-12">
        <span x-html="$icon('spinner', 'h-8 w-8 text-purple-600')"></span>
    </div>

    <!-- Tier Tabs -->
    <div x-show="!loading" x-cloak>
        <!-- Tab Navigation -->
        <div class="border-b border-gray-200 dark:border-gray-700 mb-6">
            <nav class="-mb-px flex space-x-8">
                <template x-for="tier in tiers" :key="tier.code">
                    <button
                        @click="selectedTier = tier.code"
                        :class="{
                            'border-purple-500 text-purple-600 dark:text-purple-400': selectedTier === tier.code,
                            'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300': selectedTier !== tier.code
                        }"
                        class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors">
                        <span x-text="tier.name"></span>
                        <span class="ml-2 px-2 py-0.5 text-xs rounded-full"
                              :class="selectedTier === tier.code ? 'bg-purple-100 text-purple-600 dark:bg-purple-900 dark:text-purple-300' : 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400'"
                              x-text="tier.feature_count"></span>
                    </button>
                </template>
            </nav>
        </div>

        <!-- Features Grid -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Available Features (for selected tier) -->
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                        Included Features
                    </h3>
                    <span class="text-sm text-gray-500 dark:text-gray-400"
                          x-text="`${getSelectedTierFeatures().length} features`"></span>
                </div>

                <div class="space-y-2 max-h-96 overflow-y-auto">
                    <template x-for="featureCode in getSelectedTierFeatures()" :key="featureCode">
                        <div class="flex items-center justify-between p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
                            <div class="flex items-center">
                                <span x-html="$icon('check-circle-filled', 'w-5 h-5 text-green-500 mr-3')"></span>
                                <div>
                                    <p class="text-sm font-medium text-gray-900 dark:text-white"
                                       x-text="getFeatureName(featureCode)"></p>
                                    <p class="text-xs text-gray-500 dark:text-gray-400"
                                       x-text="getFeatureCategory(featureCode)"></p>
                                </div>
                            </div>
                            <button
                                @click="removeFeatureFromTier(featureCode)"
                                class="text-red-500 hover:text-red-700 p-1">
                                <span x-html="$icon('x', 'w-4 h-4')"></span>
                            </button>
                        </div>
                    </template>

                    <div x-show="getSelectedTierFeatures().length === 0"
                         class="text-center py-8 text-gray-500 dark:text-gray-400">
                        No features assigned to this tier
                    </div>
                </div>
            </div>

            <!-- All Features (to add) -->
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                        Available to Add
                    </h3>
                    <select
                        x-model="categoryFilter"
                        class="text-sm border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 rounded-md">
                        <option value="">All Categories</option>
                        <template x-for="cat in categories" :key="cat">
                            <option :value="cat" x-text="cat.charAt(0).toUpperCase() + cat.slice(1)"></option>
                        </template>
                    </select>
                </div>

                <div class="space-y-2 max-h-96 overflow-y-auto">
                    <template x-for="feature in getAvailableFeatures()" :key="feature.code">
                        <div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                            <div class="flex items-center">
                                <span x-html="$icon('plus', 'w-5 h-5 text-gray-400 mr-3')"></span>
                                <div>
                                    <p class="text-sm font-medium text-gray-900 dark:text-white"
                                       x-text="feature.name"></p>
                                    <p class="text-xs text-gray-500 dark:text-gray-400"
                                       x-text="feature.category"></p>
                                </div>
                            </div>
                            <button
                                @click="addFeatureToTier(feature.code)"
                                class="text-green-500 hover:text-green-700 p-1">
                                <span x-html="$icon('plus', 'w-4 h-4')"></span>
                            </button>
                        </div>
                    </template>

                    <div x-show="getAvailableFeatures().length === 0"
                         class="text-center py-8 text-gray-500 dark:text-gray-400">
                        All features are assigned to this tier
                    </div>
                </div>
            </div>
        </div>

        <!-- Save Button -->
        <div class="mt-6 flex justify-end">
            <button
                @click="saveTierFeatures"
                :disabled="saving || !hasChanges"
                :class="{
                    'opacity-50 cursor-not-allowed': saving || !hasChanges,
                    'hover:bg-purple-700': !saving && hasChanges
                }"
                class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-purple-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500">
                <span x-show="saving" x-html="$icon('spinner', '-ml-1 mr-2 h-4 w-4 text-white')"></span>
                <span x-text="saving ? 'Saving...' : 'Save Changes'"></span>
            </button>
        </div>

        <!-- All Features Table -->
        <div class="mt-8 bg-white dark:bg-gray-800 rounded-lg shadow">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                    All Features
                </h3>
                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                    Complete list of all platform features with their minimum tier requirement.
                </p>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead class="bg-gray-50 dark:bg-gray-700">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                Feature
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                Category
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                Minimum Tier
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                Status
                            </th>
                        </tr>
                    </thead>
                    <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                        <template x-for="feature in allFeatures" :key="feature.code">
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-gray-900 dark:text-white" x-text="feature.name"></div>
                                    <div class="text-xs text-gray-500 dark:text-gray-400" x-text="feature.code"></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-2 py-1 text-xs rounded-full bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300"
                                          x-text="feature.category"></span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-2 py-1 text-xs rounded-full"
                                          :class="{
                                              'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300': feature.minimum_tier_code === 'essential',
                                              'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300': feature.minimum_tier_code === 'professional',
                                              'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300': feature.minimum_tier_code === 'business',
                                              'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-300': feature.minimum_tier_code === 'enterprise',
                                              'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300': !feature.minimum_tier_code
                                          }"
                                          x-text="feature.minimum_tier_name || 'N/A'"></span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span x-show="feature.is_active"
                                          class="px-2 py-1 text-xs rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300">
                                        Active
                                    </span>
                                    <span x-show="!feature.is_active"
                                          class="px-2 py-1 text-xs rounded-full bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300">
                                        Inactive
                                    </span>
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
function featuresPage() {
    return {
        ...data(),

        // State
        loading: true,
        saving: false,
        tiers: [],
        allFeatures: [],
        categories: [],
        selectedTier: 'essential',
        categoryFilter: '',
        originalTierFeatures: {},  // To track changes
        currentTierFeatures: {},   // Current state

        // Computed
        get hasChanges() {
            const original = this.originalTierFeatures[this.selectedTier] || [];
            const current = this.currentTierFeatures[this.selectedTier] || [];
            return JSON.stringify(original.sort()) !== JSON.stringify(current.sort());
        },

        // Lifecycle
        async init() {
            // Call parent init
            const path = window.location.pathname;
            const segments = path.split('/').filter(Boolean);
            this.currentPage = segments[segments.length - 1] || 'features';

            await this.loadData();
        },

        // Methods
        async loadData() {
            try {
                this.loading = true;

                // Load tiers and features in parallel
                const [tiersResponse, featuresResponse, categoriesResponse] = await Promise.all([
                    apiClient.get('/admin/features/tiers'),
                    apiClient.get('/admin/features'),
                    apiClient.get('/admin/features/categories'),
                ]);

                this.tiers = tiersResponse.tiers;
                this.allFeatures = featuresResponse.features;
                this.categories = categoriesResponse.categories;

                // Initialize tier features tracking
                for (const tier of this.tiers) {
                    this.originalTierFeatures[tier.code] = [...tier.features];
                    this.currentTierFeatures[tier.code] = [...tier.features];
                }

            } catch (error) {
                console.error('Failed to load features:', error);
                this.showNotification('Failed to load features', 'error');
            } finally {
                this.loading = false;
            }
        },

        getSelectedTierFeatures() {
            return this.currentTierFeatures[this.selectedTier] || [];
        },

        getAvailableFeatures() {
            const tierFeatures = this.getSelectedTierFeatures();
            return this.allFeatures.filter(f => {
                const notIncluded = !tierFeatures.includes(f.code);
                const matchesCategory = !this.categoryFilter || f.category === this.categoryFilter;
                return notIncluded && matchesCategory && f.is_active;
            });
        },

        getFeatureName(code) {
            const feature = this.allFeatures.find(f => f.code === code);
            return feature?.name || code;
        },

        getFeatureCategory(code) {
            const feature = this.allFeatures.find(f => f.code === code);
            return feature?.category || 'unknown';
        },

        addFeatureToTier(featureCode) {
            if (!this.currentTierFeatures[this.selectedTier].includes(featureCode)) {
                this.currentTierFeatures[this.selectedTier].push(featureCode);
            }
        },

        removeFeatureFromTier(featureCode) {
            const index = this.currentTierFeatures[this.selectedTier].indexOf(featureCode);
            if (index > -1) {
                this.currentTierFeatures[this.selectedTier].splice(index, 1);
            }
        },

        async saveTierFeatures() {
            if (!this.hasChanges) return;

            try {
                this.saving = true;

                await apiClient.put(`/admin/features/tiers/${this.selectedTier}/features`, {
                    feature_codes: this.currentTierFeatures[this.selectedTier]
                });

                // Update original to match current
                this.originalTierFeatures[this.selectedTier] = [...this.currentTierFeatures[this.selectedTier]];

                // Update tier in tiers array
                const tier = this.tiers.find(t => t.code === this.selectedTier);
                if (tier) {
                    tier.features = [...this.currentTierFeatures[this.selectedTier]];
                    tier.feature_count = tier.features.length;
                }

                this.showNotification('Features saved successfully', 'success');

            } catch (error) {
                console.error('Failed to save features:', error);
                this.showNotification('Failed to save features', 'error');
            } finally {
                this.saving = false;
            }
        },

        showNotification(message, type = 'info') {
            // Simple alert for now - could be improved with toast notifications
            if (type === 'error') {
                alert('Error: ' + message);
            } else {
                console.log(message);
            }
        }
    };
}
</script>
{% endblock %}
