<x-app-layout>

    <x-module-hero title="Theme Management" description="Control the visual appearance of the entire system with pre-configured themes" icon="fa-palette">
        <x-slot name="tabs">
            @can('view users')
            <a href="{{ route('users.index') }}"
               class="module-hero-tab {{ request()->routeIs('users.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-users text-sm"></i> Users
            </a>
            @endcan
            @role('Super Manager')
            <a href="{{ route('roles.index') }}"
               class="module-hero-tab {{ request()->routeIs('roles.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-user-tag text-sm"></i> Roles
            </a>
            <a href="{{ route('roles.assign') }}"
               class="module-hero-tab {{ request()->routeIs('roles.assign') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-key text-sm"></i> Permissions
            </a>
            @endrole
            @can('manage themes')
            <a href="{{ route('admin.themes.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.themes.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-palette text-sm"></i> Themes
            </a>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-6">

        @if(session('success'))
            <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center gap-2">
                <i class="fas fa-check-circle"></i> {{ session('success') }}
            </div>
        @endif
        @if(session('error'))
            <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center gap-2">
                <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
            </div>
        @endif

        {{-- Theme Stats Summary --}}
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div class="bg-white rounded-lg border border-gray-200 p-4 flex items-center justify-between shadow-sm">
                <div>
                    <p class="text-xs text-gray-500 font-medium uppercase tracking-wide">Total Themes</p>
                    <p class="text-2xl font-bold text-gray-800 mt-1">{{ $themes->count() }}</p>
                </div>
                <i class="fas fa-palette text-3xl text-purple-300"></i>
            </div>
            <div class="bg-white rounded-lg border border-gray-200 p-4 flex items-center justify-between shadow-sm">
                <div>
                    <p class="text-xs text-gray-500 font-medium uppercase tracking-wide">Active Theme</p>
                    <p class="text-lg font-bold text-gray-800 mt-1">{{ $activeTheme?->name ?? 'None' }}</p>
                </div>
                <i class="fas fa-check-circle text-3xl text-green-300"></i>
            </div>
            <div class="bg-white rounded-lg border border-gray-200 p-4 flex items-center justify-between shadow-sm">
                <div>
                    <p class="text-xs text-gray-500 font-medium uppercase tracking-wide">Last Updated</p>
                    <p class="text-lg font-bold text-gray-800 mt-1">{{ $activeTheme?->updated_at?->diffForHumans() ?? 'Never' }}</p>
                </div>
                <i class="fas fa-clock text-3xl text-blue-300"></i>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <div class="p-6">

                <div x-data="{
                    selectedTheme: {{ $activeTheme?->id ?? 'null' }},
                    isApplying: false,
                    previewMode: false,
                    previewTheme: null,

                    async applyTheme(themeId) {
                        if (this.isApplying) return;
                        this.isApplying = true;
                        try {
                            const response = await fetch('{{ route('admin.themes.apply') }}', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                                body: JSON.stringify({ theme_id: themeId })
                            });
                            const data = await response.json();
                            if (data.success) {
                                this.selectedTheme = themeId;
                                window.showToast('Theme applied successfully!', 'success');
                                setTimeout(() => window.location.reload(), 1000);
                            } else {
                                window.showToast(data.message || 'Failed to apply theme', 'error');
                            }
                        } catch (e) {
                            window.showToast('Network error occurred', 'error');
                        } finally {
                            this.isApplying = false;
                        }
                    },

                    async openPreview(themeId) {
                        try {
                            const response = await fetch(`{{ route('admin.themes.preview', '') }}/${themeId}`);
                            const data = await response.json();
                            if (data.success) { this.previewTheme = data.theme; this.previewMode = true; }
                        } catch (e) { console.error('Preview failed:', e); }
                    }
                }">

                    {{-- Theme Grid --}}
                    @if($themes->isNotEmpty())
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                            @foreach($themes as $theme)
                                <div class="relative group">
                                    <x-theme-preview :theme="$theme" :isActive="$activeTheme && $activeTheme->id === $theme->id" />
                                    <div class="mt-3 flex gap-2">
                                        @if($activeTheme && $activeTheme->id === $theme->id)
                                            <button disabled class="flex-1 px-3 py-2 bg-green-500 text-white rounded-lg cursor-not-allowed opacity-75 text-sm font-medium">
                                                <i class="fas fa-check mr-1"></i> Active Theme
                                            </button>
                                        @else
                                            @can('manage themes')
                                            <button @click="applyTheme({{ $theme->id }})" :disabled="isApplying"
                                                class="flex-1 px-3 py-2 bg-[#1a4731] text-white rounded-lg hover:bg-[#276749] transition text-sm font-medium disabled:opacity-50">
                                                <span x-show="!isApplying"><i class="fas fa-paint-brush mr-1"></i> Apply</span>
                                                <span x-show="isApplying"><i class="fas fa-spinner fa-spin mr-1"></i> Applying...</span>
                                            </button>
                                            @endcan
                                        @endif
                                        <button @click="openPreview({{ $theme->id }})"
                                            class="px-3 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @else
                        <div class="text-center py-12">
                            <i class="fas fa-palette text-5xl text-gray-300 mb-3"></i>
                            <p class="text-gray-500 font-medium">No themes available</p>
                            <p class="text-gray-400 text-sm mt-1">Run the theme seeder to populate themes</p>
                        </div>
                    @endif

                    {{-- Preview Modal --}}
                    <div x-show="previewMode"
                         x-transition:enter="transition ease-out duration-200"
                         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"
                         class="fixed inset-0 z-50 overflow-y-auto"
                         x-cloak>
                        <div class="fixed inset-0 bg-black/50" @click="previewMode = false"></div>
                        <div class="relative min-h-screen flex items-center justify-center p-4">
                            <div class="bg-white rounded-lg shadow-xl max-w-5xl w-full overflow-hidden relative z-10">
                                <div class="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-purple-600 to-purple-700">
                                    <h3 class="text-base font-semibold text-white flex items-center gap-2">
                                        <i class="fas fa-eye"></i> Theme Preview
                                    </h3>
                                    <button @click="previewMode = false" class="text-white/80 hover:text-white transition">
                                        <i class="fas fa-times text-xl"></i>
                                    </button>
                                </div>
                                <div class="p-6">
                                <div x-show="previewTheme">
                                    <div class="mb-4">
                                        <h4 class="text-base font-semibold text-gray-900" x-text="previewTheme?.name"></h4>
                                        <p class="text-sm text-gray-500" x-text="previewTheme?.description"></p>
                                    </div>
                                    <div class="mb-5">
                                        <h5 class="text-xs font-semibold text-gray-600 uppercase tracking-wide mb-2">Color Palette</h5>
                                        <div class="flex gap-3">
                                            <div class="text-center">
                                                <div class="w-10 h-10 rounded-lg border border-gray-200 mb-1" :style="`background-color: ${previewTheme?.primary_color}`"></div>
                                                <span class="text-xs text-gray-500">Primary</span>
                                            </div>
                                            <div class="text-center">
                                                <div class="w-10 h-10 rounded-lg border border-gray-200 mb-1" :style="`background-color: ${previewTheme?.secondary_color}`"></div>
                                                <span class="text-xs text-gray-500">Secondary</span>
                                            </div>
                                            <div class="text-center">
                                                <div class="w-10 h-10 rounded-lg border border-gray-200 mb-1" :style="`background-color: ${previewTheme?.accent_color}`"></div>
                                                <span class="text-xs text-gray-500">Accent</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mb-5 p-4 rounded-lg border"
                                         :style="`background-color: ${previewTheme?.background_card}; color: ${previewTheme?.font_color_body}`">
                                        <h6 class="font-semibold mb-1" :style="`color: ${previewTheme?.font_color_heading}; font-family: ${previewTheme?.font_family_heading}`">
                                            Sample Heading
                                        </h6>
                                        <p class="text-sm" :style="`font-family: ${previewTheme?.font_family_body}`">
                                            This is sample body text to show how the theme looks.
                                        </p>
                                        <a href="#" class="text-sm" :style="`color: ${previewTheme?.font_color_link}`">Sample Link</a>
                                    </div>
                                </div>
                                <div class="flex justify-end gap-2">
                                    <button @click="previewMode = false"
                                        class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm">
                                        Close
                                    </button>
                                    @can('manage themes')
                                    <button @click="applyTheme(previewTheme?.id); previewMode = false"
                                        x-show="previewTheme && selectedTheme !== previewTheme?.id"
                                        class="px-4 py-2 bg-[#1a4731] text-white rounded-lg hover:bg-[#276749] transition text-sm font-medium">
                                        <i class="fas fa-paint-brush mr-1"></i> Apply This Theme
                                    </button>
                                    @endcan
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>

</x-app-layout>
