@extends('admin.layouts.app')

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

@section('content')

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

    <!-- Header Actions -->
    <div class="card">
        <div class="flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between">
            <div class="flex items-center gap-3 flex-1">
                <form method="GET" action="{{ route('admin.notifications.index') }}" class="flex-1">
                    <x-search-input 
                        name="search" 
                        :value="request('search')" 
                        :placeholder="admin_trans('search_notifications')" 
                        class="w-full max-w-md"
                    />
                </form>

                <!-- Filters -->
                <div class="flex items-center gap-2">
                    <x-filter-dropdown 
                        :label="admin_trans('status')" 
                        :options="array_combine($statuses, array_map(fn($s) => admin_trans($s), $statuses))"
                    />
                    
                    <x-filter-dropdown 
                        :label="admin_trans('type')" 
                        :options="array_combine($types, array_map(fn($t) => admin_trans($t), $types))"
                    />
                </div>
            </div>

            <x-button 
                variant="primary" 
                icon="plus"
                href="{{ route('admin.notifications.create') }}"
            >
                {{ admin_trans('create_notification') }}
            </x-button>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4" x-data="notificationStats()" x-init="loadStats()">
        
        <div class="card hover:shadow-xl transition-all hover:-translate-y-1">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-secondary">{{ admin_trans('total_notifications') }}</p>
                    <h3 class="text-3xl font-bold mt-2 text-primary" x-text="stats.total || 0">0</h3>
                </div>
                <div class="w-14 h-14 rounded-xl flex items-center justify-center gradient-primary shadow-lg">
                    <i data-lucide="bell" class="w-7 h-7 text-white"></i>
                </div>
            </div>
        </div>
        
        <div class="card hover:shadow-xl transition-all hover:-translate-y-1">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-secondary">{{ admin_trans('pending') }}</p>
                    <h3 class="text-3xl font-bold mt-2 text-primary" x-text="stats.pending || 0">0</h3>
                </div>
                <div class="w-14 h-14 rounded-xl flex items-center justify-center bg-gradient-to-r from-yellow-500 to-orange-600 shadow-lg">
                    <i data-lucide="clock" class="w-7 h-7 text-white"></i>
                </div>
            </div>
        </div>
        
        <div class="card hover:shadow-xl transition-all hover:-translate-y-1">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-secondary">{{ admin_trans('sent') }}</p>
                    <h3 class="text-3xl font-bold mt-2 text-primary" x-text="stats.sent || 0">0</h3>
                </div>
                <div class="w-14 h-14 rounded-xl flex items-center justify-center bg-gradient-to-r from-green-500 to-green-600 shadow-lg">
                    <i data-lucide="check-circle" class="w-7 h-7 text-white"></i>
                </div>
            </div>
        </div>
        
        <div class="card hover:shadow-xl transition-all hover:-translate-y-1">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-secondary">{{ admin_trans('failed') }}</p>
                    <h3 class="text-3xl font-bold mt-2 text-primary" x-text="stats.failed || 0">0</h3>
                </div>
                <div class="w-14 h-14 rounded-xl flex items-center justify-center bg-gradient-to-r from-red-500 to-red-600 shadow-lg">
                    <i data-lucide="x-circle" class="w-7 h-7 text-white"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Bulk Actions Bar -->
    <div x-show="selectedItems.length > 0" x-cloak class="card bg-blue-50 border-blue-200">
        <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
                <span class="text-sm font-medium text-blue-800"
                    x-text="`${selectedItems.length} {{ admin_trans('items_selected') }}`"></span>
                <x-button size="sm" variant="outline" @click="clearSelection()">
                    {{ admin_trans('clear_selection') }}
                </x-button>
            </div>

            <div class="flex items-center gap-2">
                <x-button size="sm" variant="outline" @click="performBulkAction('resend')">
                    {{ admin_trans('resend') }}
                </x-button>
                <x-button size="sm" variant="danger" @click="performBulkAction('delete')">
                    {{ admin_trans('delete') }}
                </x-button>
            </div>
        </div>
    </div>

    <!-- Notifications Table -->
    <div class="card">
        @if ($notifications->isEmpty())
            @if(request('search'))
                <x-empty-state 
                    icon="search-x"
                    :title="admin_trans('no_results_found')"
                    :description="admin_trans('try_different_search')"
                >
                    <x-button 
                        variant="outline"
                        icon="x"
                        onclick="window.location.href='{{ route('admin.notifications.index') }}'"
                    >
                        {{ admin_trans('clear') }}
                    </x-button>
                </x-empty-state>
            @else
                <x-empty-state 
                    icon="bell"
                    :title="admin_trans('no_notifications_yet')"
                    :description="admin_trans('start_by_creating_first_notification')"
                >
                    <x-button 
                        variant="primary"
                        icon="plus"
                        href="{{ route('admin.notifications.create') }}"
                    >
                        {{ admin_trans('create_notification') }}
                    </x-button>
                </x-empty-state>
            @endif
        @else
            <!-- Notifications Table -->
            <x-enhanced-table 
                :headers="[
                    'select' => [
                        'text' => '',
                        'align' => 'center',
                        'width' => '50px'
                    ],
                    'type' => [
                        'text' => admin_trans('type'),
                        'align' => 'center',
                        'width' => '100px'
                    ],
                    'title' => [
                        'text' => admin_trans('title'),
                        'align' => 'auto',
                        'width' => '300px'
                    ],
                    'priority' => [
                        'text' => admin_trans('priority'),
                        'align' => 'center',
                        'width' => '80px'
                    ],
                    'channels' => [
                        'text' => admin_trans('channels'),
                        'align' => 'center',
                        'width' => '120px'
                    ],
                    'targets' => [
                        'text' => admin_trans('targets'),
                        'align' => 'center',
                        'width' => '100px'
                    ],
                    'status' => [
                        'text' => admin_trans('status'),
                        'align' => 'center',
                        'width' => '100px'
                    ],
                    'created_at' => [
                        'text' => admin_trans('created_at'),
                        'align' => 'center',
                        'width' => '130px'
                    ],
                    'actions' => [
                        'text' => admin_trans('actions'),
                        'align' => 'center',
                        'width' => '140px'
                    ]
                ]"
                :responsive="true"
            >
                @foreach($notifications as $notification)
                <tr class="notification-row hover:bg-primary-light transition-colors" data-id="{{ $notification->id }}">
                    
                    <!-- Select Checkbox -->
                    <x-table-cell type="center">
                        <input type="checkbox" value="{{ $notification->id }}"
                            @change="toggleItem('{{ $notification->id }}')"
                            :checked="selectedItems.includes('{{ $notification->id }}')"
                            class="checkbox notification-checkbox">
                    </x-table-cell>

                    <!-- Type -->
                    <x-table-cell type="center">
                        @php
                            $typeColors = [
                                'system' => 'info',
                                'promotional' => 'warning', 
                                'offer' => 'success',
                                'store' => 'primary',
                                'brand' => 'secondary',
                                'user' => 'purple'
                            ];
                        @endphp
                        <x-badge variant="{{ $typeColors[$notification->type] ?? 'info' }}">
                            {{ admin_trans($notification->type) }}
                        </x-badge>
                    </x-table-cell>

                    <!-- Title & Message -->
                    <x-table-cell type="text">
                        <div>
                            <span class="text-sm font-medium text-primary">
                                {{ Str::limit($notification->title, 40) }}
                            </span>
                            <div class="text-xs text-tertiary mt-1 line-clamp-2">
                                {{ Str::limit($notification->message, 80) }}
                            </div>
                        </div>
                    </x-table-cell>

                    <!-- Priority -->
                    <x-table-cell type="center">
                        @php
                            $priorityVariant = match(true) {
                                $notification->priority >= 8 => 'danger',
                                $notification->priority >= 5 => 'warning',
                                default => 'info'
                            };
                        @endphp
                        <x-badge variant="{{ $priorityVariant }}">
                            {{ $notification->priority }}
                        </x-badge>
                    </x-table-cell>

                    <!-- Channels -->
                    <x-table-cell type="center">
                        <div class="flex flex-wrap gap-1 justify-center">
                            @foreach($notification->channels as $channel)
                                <x-badge variant="secondary" class="text-xs">
                                    {{ admin_trans($channel) }}
                                </x-badge>
                            @endforeach
                        </div>
                    </x-table-cell>

                    <!-- Targets Count -->
                    <x-table-cell type="center">
                        <x-badge variant="info">
                            {{ $notification->targets->count() }}
                        </x-badge>
                    </x-table-cell>

                    <!-- Status -->
                    <x-table-cell type="center">
                        @php
                            $statusVariant = match($notification->status) {
                                'sent' => 'success',
                                'failed' => 'danger',
                                'pending' => 'warning',
                                default => 'info'
                            };
                        @endphp
                        <x-badge variant="{{ $statusVariant }}">
                            {{ admin_trans($notification->status) }}
                        </x-badge>
                    </x-table-cell>

                    <!-- Created At -->
                    <x-table-cell type="center">
                        <div class="text-sm text-tertiary">
                            {{ $notification->created_at->format('M d, Y') }}
                            <div class="text-xs">{{ $notification->created_at->format('H:i') }}</div>
                        </div>
                    </x-table-cell>

                    <!-- Actions -->
                    <x-table-cell type="actions">
                        <div class="flex items-center justify-center gap-2">
                            <!-- View Details -->
                            <a href="{{ route('admin.notifications.show', $notification) }}"
                               class="p-2 rounded-lg hover:bg-blue-50 text-blue-600 transition-colors"
                               title="{{ admin_trans('view_details') }}">
                                <i data-lucide="eye" class="w-4 h-4"></i>
                            </a>

                            @if($notification->status === 'failed')
                                <!-- Resend Button -->
                                <form method="POST" action="{{ route('admin.notifications.resend', $notification) }}" class="inline">
                                    @csrf
                                    <button type="submit"
                                            class="p-2 rounded-lg hover:bg-green-50 text-green-600 transition-colors"
                                            title="{{ admin_trans('resend') }}">
                                        <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                                    </button>
                                </form>
                            @endif

                            <!-- Delete Button -->
                            <button class="p-2 rounded-lg hover:bg-red-50 text-red-600 transition-colors"
                                    onclick="confirmDelete('{{ $notification->id }}', '{{ addslashes($notification->title) }}')"
                                    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>

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

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

@endsection

@push('scripts')
<script>
// Alpine.js Notifications Page Component
function notificationsPage() {
    return {
        selectedItems: [],

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

        toggleAll(event) {
            if (event.target.checked) {
                this.selectedItems = Array.from(document.querySelectorAll('.notification-row')).map(row => row.dataset.id);
                document.querySelectorAll('.notification-checkbox').forEach(cb => cb.checked = true);
            } else {
                this.selectedItems = [];
                document.querySelectorAll('.notification-checkbox').forEach(cb => cb.checked = false);
            }
        },

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

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

            if (action === 'delete') {
                if (!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/notifications/bulk-action', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

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

// Alpine.js Notification Stats Component
function notificationStats() {
    return {
        stats: {},

        async loadStats() {
            try {
                const response = await fetch('/admin/notifications/stats');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const result = await response.json();
                
                if (result.success) {
                    this.stats = result.stats;
                } else {
                    console.warn('Failed to load stats:', result);
                }
            } catch (error) {
                console.error('Error loading stats:', error);
                // Set default values on error
                this.stats = {
                    total: 0,
                    pending: 0,
                    sent: 0,
                    failed: 0
                };
            }
        }
    }
}

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

// Auto refresh stats every 30 seconds
setInterval(() => {
    if (window.Alpine && Alpine.store) {
        // Refresh stats if available
        const statsComponent = document.querySelector('[x-data*="notificationStats"]');
        if (statsComponent && statsComponent._x_dataStack) {
            statsComponent._x_dataStack[0].loadStats();
        }
    }
}, 30000);

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Lucide icons for dynamically added content
    if (window.lucide) {
        lucide.createIcons();
    }
});
</script>
@endpush