@extends('layouts.app')

@section('title', 'Notificaciones')
@section('page-title', 'Notificaciones y avisos')

@section('page-actions')
<div class="d-flex gap-2">
    <a href="{{ route('admin.dashboard') }}" class="btn btn-sm btn-outline-secondary">
        <i class="fas fa-arrow-left me-1"></i> Dashboard
    </a>
    <a href="{{ route('admin.usuarios') }}" class="btn btn-sm btn-outline-primary">
        <i class="fas fa-users me-1"></i> Usuarios
    </a>
</div>
@endsection

@section('content')
@php use Illuminate\Support\Str; @endphp
@php
    $estadoOptions = [
        'todas' => 'Todas',
        'sin_leer' => 'Sin leer',
        'leidas' => 'Leídas',
    ];

    $prioridadOptions = [
        'todas' => 'Todas',
        'alta' => 'Alta',
        'media' => 'Media',
        'baja' => 'Baja',
    ];

    $tipoOptions = collect($resumenTipos)
        ->pluck('tipo')
        ->filter()
        ->unique()
        ->mapWithKeys(fn($tipo) => [$tipo => ucfirst($tipo)])
        ->prepend('Todos', 'todos')
        ->toArray();

    if (!isset($tipoOptions['todos'])) {
        $tipoOptions = ['todos' => 'Todos'] + $tipoOptions;
    }

    $ordenOptions = [
        'recientes' => 'Más recientes',
        'prioridad' => 'Prioridad',
        'tipo' => 'Tipo',
    ];

    $iconoPrioridad = [
        'alta' => 'fa-circle-exclamation text-danger',
        'media' => 'fa-circle text-warning',
        'baja' => 'fa-circle text-muted',
    ];
@endphp

<div class="row g-3 mb-1">
    <div class="col-xl-3 col-md-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Total notificaciones</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['total']) }}</h4>
                    </div>
                    <span class="icon-circle bg-primary-subtle text-primary"><i class="fas fa-bell"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Sin leer</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['sin_leer']) }}</h4>
                    </div>
                    <span class="icon-circle bg-warning-subtle text-warning"><i class="fas fa-envelope-open-text"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Leídas</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['leidas']) }}</h4>
                    </div>
                    <span class="icon-circle bg-success-subtle text-success"><i class="fas fa-check"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Últimas 24 horas</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['ultimas_24h']) }}</h4>
                    </div>
                    <span class="icon-circle bg-info-subtle text-info"><i class="fas fa-bolt"></i></span>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 mb-3">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-xxl-2 col-lg-3 col-md-4">
                <label for="estado" class="form-label small text-uppercase text-muted mb-1">Estado</label>
                <select id="estado" name="estado" class="form-select form-select-sm">
                    @foreach($estadoOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['estado'] === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xxl-2 col-lg-3 col-md-4">
                <label for="prioridad" class="form-label small text-uppercase text-muted mb-1">Prioridad</label>
                <select id="prioridad" name="prioridad" class="form-select form-select-sm">
                    @foreach($prioridadOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['prioridad'] === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xxl-2 col-lg-3 col-md-4">
                <label for="tipo" class="form-label small text-uppercase text-muted mb-1">Tipo</label>
                <select id="tipo" name="tipo" class="form-select form-select-sm">
                    @foreach($tipoOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['tipo'] === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xxl-2 col-lg-3 col-md-4">
                <label for="orden" class="form-label small text-uppercase text-muted mb-1">Orden</label>
                <select id="orden" name="orden" class="form-select form-select-sm">
                    @foreach($ordenOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['orden'] === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xxl-2 col-lg-3 col-md-4">
                <label for="q" class="form-label small text-uppercase text-muted mb-1">Buscar</label>
                <input type="search" id="q" name="q" value="{{ $filtros['q'] }}" class="form-control form-control-sm" placeholder="Título, mensaje, usuario">
            </div>
            <div class="col-xxl-1 col-md-2">
                <label for="por_pagina" class="form-label small text-uppercase text-muted mb-1">Por página</label>
                <input type="number" min="5" max="100" id="por_pagina" name="por_pagina" value="{{ $filtros['por_pagina'] }}" class="form-control form-control-sm">
            </div>
            <div class="col-xxl-1 col-md-2 d-flex gap-2">
                <button type="submit" class="btn btn-sm btn-primary flex-fill">
                    <i class="fas fa-filter me-1"></i> Aplicar
                </button>
                <a href="{{ route('admin.notificaciones') }}" class="btn btn-sm btn-outline-secondary" title="Limpiar filtros">
                    <i class="fas fa-rotate-right"></i>
                </a>
            </div>
        </form>
    </div>
</div>

<div class="row g-3">
    <div class="col-xxl-9">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-0">Historial de notificaciones</h6>
                    <small class="text-muted">Mostrando {{ $notificaciones->firstItem() ?? 0 }}-{{ $notificaciones->lastItem() ?? 0 }} de {{ $notificaciones->total() }} registros</small>
                </div>
                <span class="badge bg-primary-subtle text-primary">{{ strtoupper($filtros['estado']) }}</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Detalle</th>
                                <th>Usuario</th>
                                <th class="text-center">Prioridad</th>
                                <th class="text-center">Estado</th>
                                <th class="text-end">Creada</th>
                            </tr>
                        </thead>
                        <tbody>
                        @forelse($notificaciones as $notificacion)
                            @php
                                $prioridad = $notificacion->prioridad ?? 'media';
                                $iconClass = $iconoPrioridad[$prioridad] ?? 'fa-circle text-muted';
                            @endphp
                            <tr>
                                <td>
                                    <div class="fw-semibold">{{ $notificacion->titulo }}</div>
                                    <small class="text-muted">{{ Str::limit($notificacion->mensaje, 120) }}</small>
                                    @if($notificacion->url_accion)
                                        <div class="mt-1 small"><a href="{{ $notificacion->url_accion }}" target="_blank">Ver acción</a></div>
                                    @endif
                                </td>
                                <td>
                                    <div class="fw-semibold">{{ $notificacion->usuario->nombre ?? 'Sistema' }}</div>
                                    <small class="text-muted">{{ $notificacion->usuario->email ?? '—' }}</small>
                                </td>
                                <td class="text-center">
                                    <span class="badge text-uppercase {{ $prioridad === 'alta' ? 'bg-danger' : ($prioridad === 'media' ? 'bg-warning text-dark' : 'bg-secondary') }}">
                                        <i class="fas {{ $iconClass }} me-1"></i>{{ ucfirst($prioridad) }}
                                    </span>
                                </td>
                                <td class="text-center">
                                    @if($notificacion->leido)
                                        <span class="badge bg-success">Leída</span>
                                    @else
                                        <span class="badge bg-warning text-dark">Sin leer</span>
                                    @endif
                                </td>
                                <td class="text-end">
                                    <div class="fw-semibold">{{ $notificacion->created_at?->format('d M Y H:i') ?? 'N/D' }}</div>
                                    <small class="text-muted">
                                        @if($notificacion->leido && $notificacion->fecha_leido)
                                            Leído {{ $notificacion->fecha_leido->diffForHumans() }}
                                        @else
                                            {{ $notificacion->created_at?->diffForHumans() ?? '—' }}
                                        @endif
                                    </small>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="text-center text-muted py-5">
                                    No encontramos registros con los filtros aplicados.
                                </td>
                            </tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer bg-white border-0">
                {{ $notificaciones->links('pagination::bootstrap-5') }}
            </div>
        </div>
    </div>
    <div class="col-xxl-3">
        <div class="card shadow-sm border-0 mb-3">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0">Sin leer recientes</h6>
                <span class="badge bg-info-subtle text-info">{{ $recientesSinLeer->count() }}</span>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush">
                    @forelse($recientesSinLeer as $notif)
                        <li class="list-group-item">
                            <div class="fw-semibold">{{ $notif->titulo }}</div>
                            <small class="text-muted d-block">{{ $notif->created_at?->diffForHumans() ?? '—' }}</small>
                            <small class="text-muted">{{ $notif->usuario->nombre ?? 'Sistema' }}</small>
                        </li>
                    @empty
                        <li class="list-group-item text-center text-muted py-4">Sin pendientes recientes</li>
                    @endforelse
                </ul>
            </div>
        </div>

        <div class="card shadow-sm border-0 mb-3">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0">Resumen por tipo</h6>
                <span class="badge bg-dark-subtle text-dark">{{ $resumenTipos->sum('total') }}</span>
            </div>
            <div class="card-body">
                @forelse($resumenTipos as $resumen)
                    <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                        <div>
                            <div class="fw-semibold">{{ ucfirst($resumen->tipo ?? 'sin tipo') }}</div>
                        </div>
                        <span class="badge bg-light text-dark">{{ $resumen->total }}</span>
                    </div>
                @empty
                    <p class="text-muted mb-0">Sin registros.</p>
                @endforelse
            </div>
        </div>

        <div class="card shadow-sm border-0">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0">Resumen por prioridad</h6>
                <span class="badge bg-dark-subtle text-dark">{{ $resumenPrioridades->sum('total') }}</span>
            </div>
            <div class="card-body">
                @forelse($resumenPrioridades as $resumen)
                    <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                        <div class="fw-semibold">{{ ucfirst($resumen->prioridad ?? 'sin datos') }}</div>
                        <span class="badge bg-light text-dark">{{ $resumen->total }}</span>
                    </div>
                @empty
                    <p class="text-muted mb-0">Sin registros.</p>
                @endforelse
            </div>
        </div>
    </div>
</div>
@endsection
