@extends('admin.layouts.app')

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

@section('content')

<div class="space-y-6">
    
    <!-- Header -->
    <div class="flex items-center justify-between">
        <x-button 
            variant="outline" 
            icon="arrow-left"
            href="{{ route('admin.notifications.index') }}"
        >
            {{ admin_trans('back_to_notifications') }}
        </x-button>

        <div class="flex items-center gap-2">
            @if($notification->status === 'failed')
                <form method="POST" action="{{ route('admin.notifications.resend', $notification) }}" class="inline">
                    @csrf
                    <x-button variant="secondary" icon="refresh-cw" type="submit">
                        {{ admin_trans('resend') }}
                    </x-button>
                </form>
            @endif

            <x-button 
                variant="danger" 
                icon="trash-2"
                onclick="confirmDelete({{ $notification->id }}, '{{ addslashes($notification->title) }}')"
            >
                {{ admin_trans('delete') }}
            </x-button>
        </div>
    </div>

    <!-- Notification Info -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        <!-- Main Info -->
        <div class="lg:col-span-2 space-y-6">
            
            <!-- Basic Details -->
            <div class="card">
                <div class="flex items-start justify-between mb-6">
                    <div class="flex items-center gap-3">
                        @php
                            $typeColors = [
                                'system' => 'info',
                                'promotional' => 'warning', 
                                'offer' => 'success',
                                'store' => 'primary',
                                'brand' => 'secondary',
                                'user' => 'purple'
                            ];
                            $statusColors = [
                                'pending' => 'warning',
                                'sent' => 'success',
                                'failed' => 'danger'
                            ];
                        @endphp
                        <div class="w-12 h-12 rounded-xl flex items-center justify-center gradient-{{ $typeColors[$notification->type] ?? 'primary' }}">
                            <i data-lucide="bell" class="w-6 h-6 text-white"></i>
                        </div>
                        <div>
                            <h2 class="text-xl font-bold text-primary">{{ $notification->title }}</h2>
                            <div class="flex items-center gap-2 mt-1">
                                <x-badge variant="{{ $typeColors[$notification->type] ?? 'info' }}">
                                    {{ admin_trans($notification->type) }}
                                </x-badge>
                                <x-badge variant="{{ $statusColors[$notification->status] ?? 'info' }}">
                                    {{ admin_trans($notification->status) }}
                                </x-badge>
                            </div>
                        </div>
                    </div>

                    <div class="text-right">
                        <div class="text-sm text-tertiary">{{ admin_trans('created_at') }}</div>
                        <div class="text-sm font-medium text-primary">{{ $notification->created_at->format('M d, Y H:i') }}</div>
                    </div>
                </div>

                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-semibold text-primary mb-2">{{ admin_trans('message') }}</label>
                        <div class="p-4 rounded-lg bg-primary-light text-primary">
                            {{ $notification->message }}
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-semibold text-primary mb-2">{{ admin_trans('priority') }}</label>
                            @php
                                $priorityVariant = match(true) {
                                    $notification->priority >= 8 => 'danger',
                                    $notification->priority >= 5 => 'warning',
                                    default => 'info'
                                };
                            @endphp
                            <x-badge variant="{{ $priorityVariant }}" class="text-sm">
                                {{ $notification->priority }} - 
                                @if($notification->priority >= 8) {{ admin_trans('high') }}
                                @elseif($notification->priority >= 5) {{ admin_trans('medium') }}
                                @else {{ admin_trans('low') }}
                                @endif
                            </x-badge>
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-primary mb-2">{{ admin_trans('channels') }}</label>
                            <div class="flex flex-wrap gap-1">
                                @foreach($notification->channels as $channel)
                                    <x-badge variant="secondary">{{ admin_trans($channel) }}</x-badge>
                                @endforeach
                            </div>
                        </div>
                    </div>

                    @if($notification->data && count($notification->data) > 0)
                        <div>
                            <label class="block text-sm font-semibold text-primary mb-2">{{ admin_trans('additional_data') }}</label>
                            <div class="p-3 rounded-lg bg-gray-50 border">
                                <pre class="text-xs text-tertiary">{{ json_encode($notification->data, JSON_PRETTY_PRINT) }}</pre>
                            </div>
                        </div>
                    @endif
                </div>
            </div>

            <!-- Target Audience -->
            <div class="card">
                <h3 class="text-lg font-bold text-primary mb-4">{{ admin_trans('target_audience') }}</h3>
                
                <div class="space-y-3">
                    @foreach($notification->targets as $target)
                        <div class="flex items-center gap-3 p-3 rounded-lg bg-primary-light">
                            @php
                                $targetIcons = [
                                    'all' => 'users',
                                    'country' => 'globe',
                                    'language' => 'languages',
                                    'role' => 'user-check',
                                    'user' => 'user',
                                    'store_followers' => 'store',
                                    'brand_followers' => 'sparkles'
                                ];
                            @endphp
                            <i data-lucide="{{ $targetIcons[$target->target_type] ?? 'target' }}" class="w-5 h-5 text-primary"></i>
                            <div class="flex-1">
                                <div class="text-sm font-medium text-primary">
                                    {{ admin_trans($target->target_type) }}
                                    @if($target->target_id)
                                        @switch($target->target_type)
                                            @case('country')
                                                @php $country = \App\Models\Country::find($target->target_id); @endphp
                                                @if($country) : {{ $country->name }} @endif
                                                @break
                                            @case('language')
                                                @php $language = \App\Models\Language::find($target->target_id); @endphp
                                                @if($language) : {{ $language->name }} @endif
                                                @break
                                            @case('store_followers')
                                                @php $store = \App\Models\CountryStore::find($target->target_id); @endphp
                                                @if($store) : {{ $store->store->getName() }} @endif
                                                @break
                                            @case('brand_followers')
                                                @php $brand = \App\Models\Brand::find($target->target_id); @endphp
                                                @if($brand) : {{ $brand->getName() }} @endif
                                                @break
                                            @default
                                                : {{ $target->target_id }}
                                        @endswitch
                                    @endif
                                </div>
                                <div class="text-xs text-tertiary">
                                    {{ $target->getTargetUsers()->count() }} {{ admin_trans('users') }}
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>

            <!-- Delivery History -->
            <div class="card">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-bold text-primary">{{ admin_trans('delivery_history') }}</h3>
                    <a href="{{ route('admin.notifications.delivery-report', $notification) }}"
                       class="text-sm text-primary hover:underline">
                        {{ admin_trans('view_full_report') }} →
                    </a>
                </div>

                @if($notification->deliveries->isEmpty())
                    <div class="text-center py-8 text-tertiary">
                        <i data-lucide="inbox" class="w-12 h-12 mx-auto mb-4 opacity-50"></i>
                        <p>{{ admin_trans('no_deliveries_yet') }}</p>
                    </div>
                @else
                    <div class="space-y-2 max-h-64 overflow-y-auto">
                        @foreach($notification->deliveries->take(10) as $delivery)
                            <div class="flex items-center gap-3 p-3 rounded-lg hover:bg-primary-light transition-colors">
                                <div class="w-8 h-8 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
                                    {{ substr($delivery->user->name, 0, 1) }}
                                </div>
                                <div class="flex-1">
                                    <div class="text-sm font-medium text-primary">{{ $delivery->user->name }}</div>
                                    <div class="text-xs text-tertiary">{{ $delivery->user->email }}</div>
                                </div>
                                <div class="text-right">
                                    @php
                                        $deliveryStatusColors = [
                                            'pending' => 'warning',
                                            'sent' => 'info',
                                            'read' => 'success',
                                            'failed' => 'danger'
                                        ];
                                    @endphp
                                    <x-badge variant="{{ $deliveryStatusColors[$delivery->status] ?? 'info' }}" class="text-xs">
                                        {{ admin_trans($delivery->status) }}
                                    </x-badge>
                                    <div class="text-xs text-tertiary mt-1">
                                        {{ $delivery->created_at->diffForHumans() }}
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                @endif
            </div>

        </div>

        <!-- Stats Sidebar -->
        <div class="space-y-6">
            
            <!-- Delivery Stats -->
            <div class="card">
                <h3 class="text-lg font-bold text-primary mb-4">{{ admin_trans('delivery_statistics') }}</h3>
                
                <div class="space-y-4">
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-secondary">{{ admin_trans('total_targets') }}</span>
                        <span class="text-sm font-bold text-primary">{{ number_format($stats['total_targets']) }}</span>
                    </div>
                    
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-secondary">{{ admin_trans('delivered') }}</span>
                        <span class="text-sm font-bold text-green-600">{{ number_format($stats['delivered']) }}</span>
                    </div>
                    
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-secondary">{{ admin_trans('read') }}</span>
                        <span class="text-sm font-bold text-blue-600">{{ number_format($stats['read']) }}</span>
                    </div>
                    
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-secondary">{{ admin_trans('failed') }}</span>
                        <span class="text-sm font-bold text-red-600">{{ number_format($stats['failed']) }}</span>
                    </div>
                    
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-secondary">{{ admin_trans('pending') }}</span>
                        <span class="text-sm font-bold text-yellow-600">{{ number_format($stats['pending']) }}</span>
                    </div>
                </div>

                <div class="mt-6 pt-4 border-t" style="border-color: var(--color-border);">
                    <div class="space-y-3">
                        <div>
                            <div class="flex items-center justify-between mb-1">
                                <span class="text-xs text-tertiary">{{ admin_trans('delivery_rate') }}</span>
                                <span class="text-xs font-semibold text-primary">{{ $stats['delivery_rate'] }}%</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-green-500 h-2 rounded-full transition-all" 
                                     style="width: {{ $stats['delivery_rate'] }}%"></div>
                            </div>
                        </div>
                        
                        <div>
                            <div class="flex items-center justify-between mb-1">
                                <span class="text-xs text-tertiary">{{ admin_trans('read_rate') }}</span>
                                <span class="text-xs font-semibold text-primary">{{ $stats['read_rate'] }}%</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-blue-500 h-2 rounded-full transition-all" 
                                     style="width: {{ $stats['read_rate'] }}%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Performance Insights -->
            <div class="card">
                <h3 class="text-lg font-bold text-primary mb-4">{{ admin_trans('insights') }}</h3>
                
                <div class="space-y-3">
                    @if($stats['delivery_rate'] >= 90)
                        <div class="flex items-start gap-3 p-3 rounded-lg bg-green-50">
                            <i data-lucide="check-circle" class="w-5 h-5 text-green-600 mt-0.5"></i>
                            <div>
                                <div class="text-sm font-medium text-green-800">{{ admin_trans('excellent_delivery') }}</div>
                                <div class="text-xs text-green-600">{{ admin_trans('high_delivery_rate_message') }}</div>
                            </div>
                        </div>
                    @elseif($stats['delivery_rate'] >= 70)
                        <div class="flex items-start gap-3 p-3 rounded-lg bg-yellow-50">
                            <i data-lucide="alert-triangle" class="w-5 h-5 text-yellow-600 mt-0.5"></i>
                            <div>
                                <div class="text-sm font-medium text-yellow-800">{{ admin_trans('good_delivery') }}</div>
                                <div class="text-xs text-yellow-600">{{ admin_trans('room_for_improvement') }}</div>
                            </div>
                        </div>
                    @else
                        <div class="flex items-start gap-3 p-3 rounded-lg bg-red-50">
                            <i data-lucide="x-circle" class="w-5 h-5 text-red-600 mt-0.5"></i>
                            <div>
                                <div class="text-sm font-medium text-red-800">{{ admin_trans('low_delivery') }}</div>
                                <div class="text-xs text-red-600">{{ admin_trans('delivery_issues_detected') }}</div>
                            </div>
                        </div>
                    @endif

                    @if($stats['read_rate'] >= 50)
                        <div class="flex items-start gap-3 p-3 rounded-lg bg-blue-50">
                            <i data-lucide="eye" class="w-5 h-5 text-blue-600 mt-0.5"></i>
                            <div>
                                <div class="text-sm font-medium text-blue-800">{{ admin_trans('good_engagement') }}</div>
                                <div class="text-xs text-blue-600">{{ admin_trans('users_reading_notifications') }}</div>
                            </div>
                        </div>
                    @else
                        <div class="flex items-start gap-3 p-3 rounded-lg bg-gray-50">
                            <i data-lucide="eye-off" class="w-5 h-5 text-gray-600 mt-0.5"></i>
                            <div>
                                <div class="text-sm font-medium text-gray-800">{{ admin_trans('low_engagement') }}</div>
                                <div class="text-xs text-gray-600">{{ admin_trans('consider_better_timing') }}</div>
                            </div>
                        </div>
                    @endif
                </div>
            </div>

            <!-- Channel Performance -->
            <div class="card">
                <h3 class="text-lg font-bold text-primary mb-4">{{ admin_trans('channel_performance') }}</h3>
                
                <div class="space-y-3">
                    @foreach($notification->channels as $channel)
                        @php
                            // Get deliveries for this channel
                            $channelDeliveries = $notification->deliveries->where('channel', $channel);
                            $channelTotal = $channelDeliveries->count();
                            $channelSuccess = $channelDeliveries->where('status', 'sent')->count() + 
                                            $channelDeliveries->where('status', 'read')->count();
                            $channelRate = $channelTotal > 0 ? round(($channelSuccess / $channelTotal) * 100, 1) : 0;
                        @endphp
                        
                        <div class="flex items-center justify-between p-3 rounded-lg bg-primary-light">
                            <div class="flex items-center gap-3">
                                @php
                                    $channelIcons = [
                                        'database' => 'database',
                                        'push' => 'smartphone',
                                        'email' => 'mail'
                                    ];
                                @endphp
                                <i data-lucide="{{ $channelIcons[$channel] ?? 'bell' }}" class="w-4 h-4 text-primary"></i>
                                <span class="text-sm font-medium text-primary">{{ admin_trans($channel) }}</span>
                            </div>
                            <div class="text-right">
                                <div class="text-sm font-bold text-primary">{{ $channelRate }}%</div>
                                <div class="text-xs text-tertiary">{{ $channelSuccess }}/{{ $channelTotal }}</div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>

        </div>
    </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>
// 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(() => {
    // Only refresh if notification is still pending or being sent
    const status = '{{ $notification->status }}';
    if (status === 'pending') {
        location.reload();
    }
}, 30000);
</script>
@endpush