@extends('admin.layouts.app')

@section('title', admin_trans('subscriptions'))
@section('page-title', admin_trans('subscriptions_management'))

@section('content')

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

    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <x-stat-card
            icon="users"
            :title="admin_trans('total_subscriptions')"
            :value="$stats['total']"
            variant="primary"
        />
        <x-stat-card
            icon="store"
            :title="admin_trans('store_followers')"
            :value="$stats['stores']"
            variant="info"
        />
        <x-stat-card
            icon="tag"
            :title="admin_trans('brand_followers')"
            :value="$stats['brands']"
            variant="warning"
        />
        <x-stat-card
            icon="grid"
            :title="admin_trans('category_followers')"
            :value="$stats['categories']"
            variant="success"
        />
    </div>

    <!-- More Statistics -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <x-stat-card
            icon="calendar"
            :title="admin_trans('today')"
            :value="$stats['today']"
            variant="secondary"
        />
        <x-stat-card
            icon="calendar-days"
            :title="admin_trans('this_week')"
            :value="$stats['this_week']"
            variant="secondary"
        />
        <x-stat-card
            icon="calendar-range"
            :title="admin_trans('this_month')"
            :value="$stats['this_month']"
            variant="secondary"
        />
    </div>

    <!-- Header: Search & Export Button -->
    <div class="card">
        <div class="flex flex-col lg:flex-row gap-4 items-start lg:items-center justify-between">

            <!-- Search -->
            <div class="flex-1 w-full max-w-lg">
                <form method="GET" action="{{ route('admin.subscriptions.index') }}">
                    @foreach(request()->except(['search', 'page']) as $key => $value)
                        @if(is_array($value))
                            @foreach($value as $v)
                                <input type="hidden" name="{{ $key }}[]" value="{{ $v }}">
                            @endforeach
                        @else
                            <input type="hidden" name="{{ $key }}" value="{{ $value }}">
                        @endif
                    @endforeach

                    <x-search-input
                        name="search"
                        :value="request('search')"
                        :placeholder="admin_trans('search_users')"
                        class="w-full"
                    />
                </form>
            </div>

            <!-- Export Button -->
            <x-button variant="outline" icon="download" href="{{ route('admin.subscriptions.export') }}">
                {{ admin_trans('export') }}
            </x-button>
        </div>
    </div>

    <!-- Advanced Filters -->
    <div class="card">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-primary">{{ admin_trans('filters') }}</h3>
            <button @click="filtersExpanded = !filtersExpanded" class="p-2 rounded-lg hover:bg-primary-light">
                <i data-lucide="filter" class="w-5 h-5 text-primary"></i>
            </button>
        </div>

        <div x-show="filtersExpanded" x-collapse class="space-y-4">
            <form method="GET" action="{{ route('admin.subscriptions.index') }}" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                @if(request('search'))<input type="hidden" name="search" value="{{ request('search') }}">@endif

                <!-- Subscribable Type Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('subscribable_type') }}</label>
                    <select name="subscribable_type" class="input text-sm">
                        <option value="">{{ admin_trans('all_types') }}</option>
                        <option value="store" {{ request('subscribable_type') === 'store' ? 'selected' : '' }}>{{ admin_trans('stores') }}</option>
                        <option value="brand" {{ request('subscribable_type') === 'brand' ? 'selected' : '' }}>{{ admin_trans('brands') }}</option>
                        <option value="category" {{ request('subscribable_type') === 'category' ? 'selected' : '' }}>{{ admin_trans('categories') }}</option>
                    </select>
                </div>

                <!-- Subscription Type Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('subscription_type') }}</label>
                    <select name="type" class="input text-sm">
                        <option value="">{{ admin_trans('all_subscription_types') }}</option>
                        <option value="follow" {{ request('type') === 'follow' ? 'selected' : '' }}>{{ admin_trans('follow') }}</option>
                        <option value="notify" {{ request('type') === 'notify' ? 'selected' : '' }}>{{ admin_trans('notify') }}</option>
                    </select>
                </div>

                <!-- User Filter -->
                @if($users->count() > 0)
                    @php
                        $usersArray = $users->map(function($user) {
                            return [
                                'id' => $user->id,
                                'name' => $user->name . ' (' . $user->email . ')'
                            ];
                        })->toArray();
                    @endphp
                    <x-searchable-select
                        name="user_id"
                        :label="admin_trans('user')"
                        :placeholder="admin_trans('search_users')"
                        :options="$usersArray"
                        :selected="request('user_id')"
                        valueKey="id"
                        labelKey="name"
                    />
                @endif

                <!-- Date Range Filters -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('date_from') }}</label>
                    <input type="date" name="date_from" value="{{ request('date_from') }}" class="input text-sm">
                </div>

                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('date_to') }}</label>
                    <input type="date" name="date_to" value="{{ request('date_to') }}" class="input text-sm">
                </div>

                <!-- Sort Options -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('sort_by') }}</label>
                    <select name="sort" class="input text-sm">
                        <option value="created_at" {{ request('sort') === 'created_at' ? 'selected' : '' }}>{{ admin_trans('date_subscribed') }}</option>
                        <option value="updated_at" {{ request('sort') === 'updated_at' ? 'selected' : '' }}>{{ admin_trans('last_update') }}</option>
                    </select>
                </div>

                <!-- Apply/Clear Buttons -->
                <div class="flex items-end gap-2">
                    <x-button type="submit" variant="primary" class="flex-1">
                        {{ admin_trans('apply_filters') }}
                    </x-button>
                </div>
            </form>

            <!-- Clear Filters -->
            @if(request()->hasAny(['search', 'subscribable_type', 'type', 'user_id', 'date_from', 'date_to', 'sort']))
                <div class="pt-3 border-t" style="border-color: var(--color-border);">
                    <x-button variant="outline" size="sm" icon="x-circle" href="{{ route('admin.subscriptions.index') }}">
                        {{ admin_trans('clear_all_filters') }}
                    </x-button>
                </div>
            @endif
        </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="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>

    <!-- Subscriptions Table -->
    <x-card>
        @if ($subscriptions->isEmpty())
            <x-empty-state icon="users" :title="admin_trans('no_subscriptions_yet')" :description="admin_trans('no_subscriptions_found')">
            </x-empty-state>
        @else
            <x-enhanced-table
                :headers="[
                    'select' => ['text' => '', 'align' => 'center', 'width' => '50px'],
                    'user' => ['text' => admin_trans('user'), 'align' => 'left', 'width' => '200px'],
                    'subscribable' => ['text' => admin_trans('subscribed_to'), 'align' => 'left', 'width' => '250px'],
                    'type' => ['text' => admin_trans('type'), 'align' => 'center', 'width' => '100px'],
                    'subscribable_type' => ['text' => admin_trans('category_type'), 'align' => 'center', 'width' => '120px'],
                    'date' => ['text' => admin_trans('subscription_date'), 'align' => 'center', 'width' => '150px'],
                    'actions' => ['text' => admin_trans('actions'), 'align' => 'center', 'width' => '100px']
                ]"
                :responsive="true"
                :striped="true"
            >
                @foreach ($subscriptions as $subscription)
                    <tr class="subscription-row hover:bg-primary-light transition-colors" data-id="{{ $subscription->id }}">

                        <!-- Select -->
                        <x-table-cell type="actions">
                            <input type="checkbox" value="{{ $subscription->id }}"
                                @change="toggleItem({{ $subscription->id }})"
                                :checked="selectedItems.includes({{ $subscription->id }})"
                                class="checkbox">
                        </x-table-cell>

                        <!-- User -->
                        <x-table-cell type="text">
                            @if($subscription->user)
                                <div class="flex items-center gap-3">
                                    <div class="w-10 h-10 rounded-xl flex items-center justify-center text-white font-bold gradient-primary text-sm">
                                        {{ substr($subscription->user->name, 0, 1) }}
                                    </div>
                                    <div>
                                        <div class="text-sm font-medium text-primary">{{ $subscription->user->name }}</div>
                                        <div class="text-xs text-tertiary">{{ $subscription->user->email }}</div>
                                    </div>
                                </div>
                            @else
                                <span class="text-xs text-tertiary">{{ admin_trans('deleted_user') }}</span>
                            @endif
                        </x-table-cell>

                        <!-- Subscribable -->
                        <x-table-cell type="text">
                            @if($subscription->subscribable)
                                <div>
                                    <div class="text-sm font-medium text-primary">{{ $subscription->subscribable->name }}</div>
                                    <div class="text-xs text-tertiary">ID: {{ $subscription->subscribable_id }}</div>
                                </div>
                            @else
                                <span class="text-xs text-tertiary">{{ admin_trans('deleted_item') }}</span>
                            @endif
                        </x-table-cell>

                        <!-- Type -->
                        <x-table-cell type="badge">
                            @php
                                $typeVariant = match($subscription->type) {
                                    'follow' => 'info',
                                    'notify' => 'warning',
                                    default => 'secondary'
                                };
                            @endphp
                            <x-badge variant="{{ $typeVariant }}" class="text-xs">
                                {{ admin_trans($subscription->type) }}
                            </x-badge>
                        </x-table-cell>

                        <!-- Subscribable Type -->
                        <x-table-cell type="badge">
                            @php
                                $modelClass = class_basename($subscription->subscribable_type);
                                $subscribableVariant = match($modelClass) {
                                    'Store' => 'primary',
                                    'Brand' => 'warning',
                                    'Category' => 'success',
                                    default => 'secondary'
                                };
                            @endphp
                            <x-badge variant="{{ $subscribableVariant }}" class="text-xs">
                                {{ admin_trans(strtolower($modelClass)) }}
                            </x-badge>
                        </x-table-cell>

                        <!-- Date -->
                        <x-table-cell type="text">
                            <div class="text-center">
                                <div class="text-xs text-tertiary">{{ $subscription->created_at->format('d/m/Y') }}</div>
                                <div class="text-xs text-tertiary">{{ $subscription->created_at->diffForHumans() }}</div>
                            </div>
                        </x-table-cell>

                        <!-- Actions -->
                        <x-table-cell type="actions">
                            <div class="flex items-center justify-center gap-2">
                                <button onclick="confirmDelete({{ $subscription->id }})" class="p-1.5 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>
                        </x-table-cell>
                    </tr>
                @endforeach
            </x-enhanced-table>

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

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

@endsection

@push('scripts')
<script>
function subscriptionsPage() {
    return {
        selectedItems: [],
        filtersExpanded: {{ request()->hasAny(['subscribable_type', 'type', 'user_id', 'date_from', 'date_to', 'sort']) ? 'true' : 'false' }},

        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/subscriptions/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 confirmDelete(id) {
    window.addEventListener('confirm-action', function handler(e) {
        if (e.detail === 'delete-subscription-modal') {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `/admin/subscriptions/${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-subscription-modal' }));
}

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