@extends('admin.layouts.app')

@section('title', admin_trans('carousels'))
@section('page-title', admin_trans('carousels'))

@section('content')

<div class="space-y-6" x-data="carouselsPage()">

    <!-- Header -->
    <div class="card">
        <div class="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
            
            <!-- Search -->
            <div class="flex-1 w-full max-w-lg">
                <form method="GET" action="{{ route('admin.carousels.index') }}">
                    @if(request('type'))<input type="hidden" name="type" value="{{ request('type') }}">@endif
                    @if(request('status'))<input type="hidden" name="status" value="{{ request('status') }}">@endif
                    
                    <x-search-input 
                        name="search" 
                        :value="request('search')" 
                        :placeholder="admin_trans('search_carousels')" 
                        class="w-full"
                    />
                </form>
            </div>

            <!-- Filters -->
            <div class="flex flex-wrap items-center gap-4">
                
                <!-- Type Filter -->
                <form method="GET" action="{{ route('admin.carousels.index') }}" class="flex items-center gap-2">
                    @if(request('search'))<input type="hidden" name="search" value="{{ request('search') }}">@endif
                    @if(request('status'))<input type="hidden" name="status" value="{{ request('status') }}">@endif
                    
                    <label class="text-sm font-medium text-tertiary">{{ admin_trans('type') }}:</label>
                    <select name="type" onchange="this.form.submit()" class="input text-sm py-2 px-3">
                        <option value="">{{ admin_trans('all_types') }}</option>
                        <option value="home" {{ request('type') === 'home' ? 'selected' : '' }}>{{ admin_trans('home') }}</option>
                        <option value="category" {{ request('type') === 'category' ? 'selected' : '' }}>{{ admin_trans('category') }}</option>
                        <option value="store" {{ request('type') === 'store' ? 'selected' : '' }}>{{ admin_trans('store') }}</option>
                        <option value="custom" {{ request('type') === 'custom' ? 'selected' : '' }}>{{ admin_trans('custom') }}</option>
                    </select>
                </form>

                <!-- Status Filter -->
                <form method="GET" action="{{ route('admin.carousels.index') }}" class="flex items-center gap-2">
                    @if(request('search'))<input type="hidden" name="search" value="{{ request('search') }}">@endif
                    @if(request('type'))<input type="hidden" name="type" value="{{ request('type') }}">@endif
                    
                    <label class="text-sm font-medium text-tertiary">{{ admin_trans('status') }}:</label>
                    <select name="status" onchange="this.form.submit()" class="input text-sm py-2 px-3">
                        <option value="">{{ admin_trans('all_statuses') }}</option>
                        <option value="active" {{ request('status') === 'active' ? 'selected' : '' }}>{{ admin_trans('active') }}</option>
                        <option value="inactive" {{ request('status') === 'inactive' ? 'selected' : '' }}>{{ admin_trans('inactive') }}</option>
                    </select>
                </form>

                <!-- Clear Filters -->
                @if(request()->hasAny(['search', 'type', 'status']))
                    <x-button variant="outline" size="sm" icon="x-circle" href="{{ route('admin.carousels.index') }}">
                        {{ admin_trans('clear_filters') }}
                    </x-button>
                @endif
            </div>

            <!-- Add Button -->
            <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-carousel-modal')">
                {{ admin_trans('add_carousel') }}
            </x-button>
        </div>
    </div>

    <!-- Bulk Actions -->
    <div x-show="selectedItems.length > 0" x-cloak>
        <x-alert variant="info">
            <div class="flex items-center justify-between w-full">
                <span x-text="`${selectedItems.length} {{ admin_trans('items_selected') }}`"></span>
                <div class="flex gap-2">
                    <x-button size="sm" variant="outline" @click="performBulkAction('activate')">{{ admin_trans('activate') }}</x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('deactivate')">{{ admin_trans('deactivate') }}</x-button>
                    <x-button size="sm" variant="danger" @click="performBulkAction('delete')">{{ admin_trans('delete') }}</x-button>
                    <x-button size="sm" variant="outline" @click="clearSelection()">{{ admin_trans('clear') }}</x-button>
                </div>
            </div>
        </x-alert>
    </div>

    <!-- Carousels Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        @forelse ($carousels as $carousel)
            <div class="card hover:shadow-xl transition-all">
                <!-- Header -->
                <div class="flex items-start justify-between mb-4">
                    <div class="flex-1">
                        <h3 class="text-lg font-bold text-primary mb-1">{{ $carousel->name }}</h3>
                        <div class="flex items-center gap-2 flex-wrap">
                            <x-badge variant="secondary" class="text-xs">
                                {{ $carousel->type }}
                            </x-badge>
                            <x-badge variant="info" class="text-xs">
                                {{ $carousel->slug }}
                            </x-badge>
                            @if($carousel->country)
                            <x-badge variant="warning" class="text-xs">
                                <i data-lucide="globe" class="w-3 h-3 inline"></i>
                                {{ $carousel->country->name }}
                            </x-badge>
                            @endif
                        </div>
                    </div>
                    <input type="checkbox" value="{{ $carousel->id }}" 
                        @change="toggleItem({{ $carousel->id }})" 
                        :checked="selectedItems.includes({{ $carousel->id }})" 
                        class="checkbox">
                </div>

                <!-- Slides Preview -->
                <div class="mb-4">
                    <div class="flex items-center gap-2 mb-2">
                        <i data-lucide="images" class="w-4 h-4 text-tertiary"></i>
                        <span class="text-sm text-secondary">{{ $carousel->slides->count() }} {{ admin_trans('slides') }}</span>
                    </div>
                    
@if($carousel->slides->count() > 0)
    <div class="flex gap-2 overflow-x-auto">
        @foreach($carousel->slides->take(3) as $slide)
            @if($slide->getFirstMediaUrl('image'))
                <img src="{{ $slide->getFirstMediaUrl('image') }}" 
                     alt="Slide" 
                     class="w-16 h-16 object-cover rounded-lg border">
            @endif
        @endforeach
        @if($carousel->slides->count() > 3)
            <div class="w-16 h-16 bg-gray-100 rounded-lg border flex items-center justify-center">
                <span class="text-xs text-tertiary font-medium">+{{ $carousel->slides->count() - 3 }}</span>
            </div>
        @endif
    </div>
@else
    <div class="py-4 text-center border rounded-lg" style="border-color: var(--color-border);">
        <i data-lucide="image-off" class="w-8 h-8 text-tertiary mx-auto mb-2"></i>
        <p class="text-xs text-tertiary">{{ admin_trans('no_slides_yet') }}</p>
    </div>
@endif
                </div>

                <!-- Footer -->
                <div class="flex items-center justify-between pt-4 border-t" style="border-color: var(--color-border);">
                    <!-- Status Toggle -->
                    <form method="POST" action="{{ route('admin.carousels.toggle-status', $carousel) }}">
                        @csrf @method('PATCH')
                        <x-toggle name="status_toggle_{{ $carousel->id }}" :checked="$carousel->is_active" size="sm" variant="success" onchange="this.form.submit()" />
                    </form>

                    <!-- Actions -->
                    <div class="flex items-center gap-2">
                        <a href="{{ route('admin.carousels.show', $carousel) }}" class="p-2 rounded-lg hover:bg-blue-50 text-blue-600" title="{{ admin_trans('manage_slides') }}">
                            <i data-lucide="layout" class="w-4 h-4"></i>
                        </a>
                        <button onclick="editCarousel({{ $carousel->id }}, '{{ $carousel->name }}', '{{ $carousel->slug }}', '{{ $carousel->type }}', {{ $carousel->country_id ?? 'null' }}, {{ $carousel->is_active ? 'true' : 'false' }})" class="p-2 rounded-lg hover:bg-green-50 text-green-600" title="{{ admin_trans('edit') }}">
                            <i data-lucide="edit-3" class="w-4 h-4"></i>
                        </button>
                        <button onclick="confirmDelete({{ $carousel->id }}, '{{ addslashes($carousel->name) }}')" class="p-2 rounded-lg hover:bg-red-50 text-red-600" title="{{ admin_trans('delete') }}">
                            <i data-lucide="trash-2" class="w-4 h-4"></i>
                        </button>
                    </div>
                </div>
            </div>
        @empty
            <div class="col-span-full">
                <x-empty-state icon="images" :title="admin_trans('no_carousels_yet')" :description="admin_trans('start_by_adding_first_carousel')">
                    <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-carousel-modal')">
                        {{ admin_trans('add_carousel') }}
                    </x-button>
                </x-empty-state>
            </div>
        @endforelse
    </div>

    @if ($carousels->hasPages())
        <div class="mt-6">
            <x-pagination :paginator="$carousels" />
        </div>
    @endif
</div>

<!-- Create Modal -->
<x-modal name="create-carousel-modal" maxWidth="lg">
    <div class="p-6">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('add_carousel') }}</h3>
            <button @click="$dispatch('close-modal', 'create-carousel-modal')" class="p-2 rounded-lg hover:bg-primary-light">
                <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
            </button>
        </div>

        <form method="POST" action="{{ route('admin.carousels.store') }}" class="space-y-6">
            @csrf
            
            <x-input :label="admin_trans('carousel_name')" name="name" :required="true" placeholder="{{ admin_trans('enter_carousel_name') }}" />
            
            <x-input :label="admin_trans('slug')" name="slug" :required="true" placeholder="home-carousel" hint="{{ admin_trans('slug_hint') }}" />
            
            <x-select :label="admin_trans('type')" name="type" :required="true">
                <option value="">{{ admin_trans('select_type') }}</option>
                <option value="home">{{ admin_trans('home') }}</option>
                <option value="category">{{ admin_trans('category') }}</option>
                <option value="store">{{ admin_trans('store') }}</option>
                <option value="custom">{{ admin_trans('custom') }}</option>
            </x-select>

            @if($currentCountry)
                <x-alert variant="info" class="text-sm">
                    <div class="flex items-center gap-2">
                        <i data-lucide="globe" class="w-4 h-4"></i>
                        <span>{{ admin_trans('will_be_created_for') }}: <strong>{{ $currentCountry->name }}</strong></span>
                    </div>
                </x-alert>
            @else
                <x-alert variant="warning" class="text-sm">
                    {{ admin_trans('please_select_country_from_navbar_first') }}
                </x-alert>
            @endif

            <x-toggle name="is_active" :label="admin_trans('active')" value="1" :checked="true" />

            <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                <x-button variant="outline" type="button" @click="$dispatch('close-modal', 'create-carousel-modal')">{{ admin_trans('cancel') }}</x-button>
                <x-button variant="primary" type="submit" icon="check">{{ admin_trans('create') }}</x-button>
            </div>
        </form>
    </div>
</x-modal>

<!-- Edit Modal -->
<x-modal name="edit-carousel-modal" maxWidth="lg">
    <div class="p-6" x-data="editCarouselModal()">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('edit_carousel') }}</h3>
            <button @click="$dispatch('close-modal', 'edit-carousel-modal')" class="p-2 rounded-lg hover:bg-primary-light">
                <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
            </button>
        </div>

        <form :action="`/admin/carousels/${carouselData?.id}`" method="POST" class="space-y-6">
            @csrf @method('PUT')
            
            <x-input 
                :label="admin_trans('carousel_name')" 
                name="name" 
                :required="true"
                x-bind:value="carouselData?.name"
                @input="carouselData.name = $event.target.value"
            />
            
            <x-input 
                :label="admin_trans('slug')" 
                name="slug" 
                :required="true"
                x-bind:value="carouselData?.slug"
                @input="carouselData.slug = $event.target.value"
            />
            
            <div>
                <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('type') }} *</label>
                <select
                    name="type"
                    required
                    class="input"
                    x-bind:value="carouselData?.type"
                    @change="carouselData.type = $event.target.value"
                >
                    <option value="">{{ admin_trans('select_type') }}</option>
                    <option value="home">{{ admin_trans('home') }}</option>
                    <option value="category">{{ admin_trans('category') }}</option>
                    <option value="store">{{ admin_trans('store') }}</option>
                    <option value="custom">{{ admin_trans('custom') }}</option>
                </select>
            </div>

            <div>
                <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('country') }} *</label>
                <select
                    name="country_id"
                    required
                    class="input"
                    x-bind:value="carouselData?.country_id"
                    @change="carouselData.country_id = $event.target.value"
                >
                    <option value="">{{ admin_trans('select_country') }}</option>
                    @foreach($countries as $country)
                        <option value="{{ $country->id }}">{{ $country->name }}</option>
                    @endforeach
                </select>
            </div>

            <div class="flex items-center gap-3">
                <input 
                    type="checkbox" 
                    name="is_active" 
                    value="1"
                    class="checkbox"
                    x-bind:checked="carouselData?.is_active"
                    @change="carouselData.is_active = $event.target.checked"
                >
                <label class="text-sm font-medium text-primary">
                    {{ admin_trans('active') }}
                </label>
            </div>

            <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                <x-button variant="outline" type="button" @click="$dispatch('close-modal', 'edit-carousel-modal')">{{ admin_trans('cancel') }}</x-button>
                <x-button variant="primary" type="submit" icon="check">{{ admin_trans('update') }}</x-button>
            </div>
        </form>
    </div>
</x-modal>

<!-- Delete Confirmation -->
<x-confirm-modal name="delete-carousel-modal" :title="admin_trans('confirm_delete')" :message="admin_trans('delete_carousel_message')" :confirmText="admin_trans('yes_delete')" :cancelText="admin_trans('cancel')" confirmVariant="danger" icon="trash-2" iconColor="danger" />

@endsection

@push('scripts')
<script>
function carouselsPage() {
    return {
        selectedItems: [],

        init() {
            // Listen to country filter changes - reload page
            window.addEventListener('country-filter-changed', () => {
                if (window.toast) {
                    toast.info('{{ admin_trans("country_changed_redirecting") }}...');
                }
                setTimeout(() => window.location.reload(), 500);
            });
        },

        toggleItem(id) {
            const index = this.selectedItems.indexOf(id);
            if (index > -1) {
                this.selectedItems.splice(index, 1);
            } else {
                this.selectedItems.push(id);
            }
        },

        clearSelection() {
            this.selectedItems = [];
            document.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
        },

        async performBulkAction(action) {
            if (this.selectedItems.length === 0) {
                if (window.toast) {
                    toast.warning('{{ admin_trans("please_select_items") }}');
                }
                return;
            }

            if (action === 'delete' && !confirm('{{ admin_trans("confirm_bulk_delete") }}')) return;

            try {
                const formData = new FormData();
                formData.append('_token', document.querySelector('meta[name="csrf-token"]').content);
                formData.append('action', action);
                this.selectedItems.forEach(id => formData.append('selected[]', id));

                const response = await fetch('/admin/carousels/bulk-action', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.success) {
                    if (window.toast) {
                        toast.success(result.message);
                    }
                    setTimeout(() => window.location.reload(), 1000);
                } else {
                    if (window.toast) {
                        toast.error(result.message);
                    }
                }
            } catch (error) {
                console.error('Bulk action error:', error);
                if (window.toast) {
                    toast.error('{{ admin_trans("error_bulk_action") }}');
                }
            }
        }
    }
}

function editCarouselModal() {
    return {
        carouselData: {
            id: null,
            name: '',
            slug: '',
            type: '',
            country_id: null,
            is_active: false
        }
    }
}

function editCarousel(id, name, slug, type, countryId, isActive) {
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'edit-carousel-modal' }));
    setTimeout(() => {
        const modal = document.querySelector('[x-data*="editCarouselModal"]');
        if (modal && modal._x_dataStack) {
            modal._x_dataStack[0].carouselData = {
                id: id,
                name: name,
                slug: slug,
                type: type,
                country_id: countryId,
                is_active: isActive
            };
        }
    }, 100);
}

function confirmDelete(id, name) {
    window.addEventListener('confirm-action', function handler(e) {
        if (e.detail === 'delete-carousel-modal') {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `/admin/carousels/${id}`;
            form.innerHTML = '@csrf @method("DELETE")';
            document.body.appendChild(form);
            form.submit();
            window.removeEventListener('confirm-action', handler);
        }
    });
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'delete-carousel-modal' }));
}

document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
});
</script>
@endpush