@extends('layouts.app')

@section('title', 'Mensajes internos')
@section('page-title', 'Mensajes')

@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.notificaciones') }}" class="btn btn-sm btn-outline-primary">
        <i class="fas fa-bell me-1"></i> Notificaciones
    </a>
</div>
@endsection

@section('content')
@php use Illuminate\Support\Str; @endphp
@php
    $estadoOptions = [
        'todos' => 'Todos',
        'enviados' => 'Enviados',
        'pendientes' => 'Pendientes',
    ];

    $ordenOptions = [
        'recientes' => 'Más recientes',
        'programados' => 'Programados',
        'enviados' => 'Fecha envío',
    ];

    $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;
    }

    $destinatarioOptions = collect($resumenDestinatarios)
        ->pluck('destinatario')
        ->filter()
        ->unique()
        ->mapWithKeys(fn($destino) => [$destino => ucfirst($destino)])
        ->prepend('Todos', 'todos')
        ->toArray();

    if (!isset($destinatarioOptions['todos'])) {
        $destinatarioOptions = ['todos' => 'Todos'] + $destinatarioOptions;
    }
@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 mensajes</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['total']) }}</h4>
                    </div>
                    <span class="icon-circle bg-dark-subtle text-dark"><i class="fas fa-inbox"></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">Enviados</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['enviados']) }}</h4>
                    </div>
                    <span class="icon-circle bg-success-subtle text-success"><i class="fas fa-paper-plane"></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">Pendientes</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['pendientes']) }}</h4>
                    </div>
                    <span class="icon-circle bg-warning-subtle text-warning"><i class="fas fa-clock"></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">Programados hoy</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['programados_hoy']) }}</h4>
                    </div>
                    <span class="icon-circle bg-info-subtle text-info"><i class="fas fa-calendar-day"></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="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="destinatario" class="form-label small text-uppercase text-muted mb-1">Destinatario</label>
                <select id="destinatario" name="destinatario" class="form-select form-select-sm">
                    @foreach($destinatarioOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['destinatario'] === $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, contenido o 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.mensajes') }}" 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 mensajes</h6>
                    <small class="text-muted">Mostrando {{ $mensajes->firstItem() ?? 0 }}-{{ $mensajes->lastItem() ?? 0 }} de {{ $mensajes->total() }} registros</small>
                </div>
                <span class="badge bg-dark-subtle text-dark">{{ 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>Mensaje</th>
                                <th>Usuario</th>
                                <th class="text-center">Tipo</th>
                                <th class="text-center">Estado</th>
                                <th class="text-end">Fechas</th>
                            </tr>
                        </thead>
                        <tbody>
                        @forelse($mensajes as $mensaje)
                            @php
                                $esEnviado = (bool) $mensaje->enviado;
                                $estadoBadge = $esEnviado ? 'bg-success' : 'bg-warning text-dark';
                                $estadoTexto = $esEnviado ? 'Enviado' : 'Pendiente';
                                $tipoTexto = $mensaje->tipo ? ucfirst($mensaje->tipo) : 'General';
                                $destinatarioTexto = $mensaje->destinatario ? ucfirst($mensaje->destinatario) : 'General';
                            @endphp
                            <tr>
                                <td>
                                    <div class="fw-semibold">{{ $mensaje->titulo ?? 'Sin título' }}</div>
                                    <small class="text-muted d-block">{{ Str::limit($mensaje->contenido ?? '', 140) }}</small>
                                    <div class="small mt-1">
                                        <span class="badge bg-light text-dark me-1">{{ $destinatarioTexto }}</span>
                                        @if($mensaje->creador)
                                            <span class="text-muted">Creado por {{ $mensaje->creador->nombre }}</span>
                                        @endif
                                    </div>
                                </td>
                                <td>
                                    <div class="fw-semibold">{{ $mensaje->usuario->nombre ?? 'Sistema' }}</div>
                                    <small class="text-muted">{{ $mensaje->usuario->email ?? '—' }}</small>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-secondary text-uppercase">{{ $tipoTexto }}</span>
                                </td>
                                <td class="text-center">
                                    <span class="badge {{ $estadoBadge }}">{{ $estadoTexto }}</span>
                                </td>
                                <td class="text-end">
                                    <div class="fw-semibold">{{ $mensaje->created_at?->format('d M Y H:i') ?? 'N/D' }}</div>
                                    <small class="text-muted d-block">Programado: {{ $mensaje->fecha_programada?->format('d M Y H:i') ?? '—' }}</small>
                                    <small class="text-muted">Enviado: {{ $mensaje->fecha_enviado?->format('d M Y H:i') ?? '—' }}</small>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="text-center text-muted py-5">No hay registros que coincidan con los filtros.</td>
                            </tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer bg-white border-0">
                {{ $mensajes->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">Pendientes próximos</h6>
                <span class="badge bg-warning-subtle text-warning">{{ $pendientes->count() }}</span>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush">
                    @forelse($pendientes as $pendiente)
                        <li class="list-group-item">
                            <div class="fw-semibold">{{ $pendiente->titulo ?? 'Sin título' }}</div>
                            <small class="text-muted d-block">{{ $pendiente->fecha_programada?->diffForHumans() ?? 'Sin fecha' }}</small>
                            <small class="text-muted">Destino {{ ucfirst($pendiente->destinatario ?? 'general') }}</small>
                        </li>
                    @empty
                        <li class="list-group-item text-center text-muted py-4">Sin envíos pendientes.</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 class="fw-semibold">{{ ucfirst($resumen->tipo ?? 'Sin tipo') }}</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 destinatario</h6>
                <span class="badge bg-dark-subtle text-dark">{{ $resumenDestinatarios->sum('total') }}</span>
            </div>
            <div class="card-body">
                @forelse($resumenDestinatarios as $resumen)
                    <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                        <div class="fw-semibold">{{ ucfirst($resumen->destinatario ?? '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
