@model IEnumerable<foundation_system.Models.AsistenciaColaborador>

@{
    ViewData["Title"] = "Reporte de Asistencia por Colaborador";
    var colaboradores = (IEnumerable<foundation_system.Models.Colaborador>)ViewBag.Colaboradores;
    var inicio = (DateOnly)ViewBag.Inicio;
    var fin = (DateOnly)ViewBag.Fin;
    var selectedColaboradorId = (long?)ViewBag.ColaboradorId;
}

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="h3 mb-0 text-gray-800"><i class="bi bi-file-earmark-bar-graph me-2"></i>@ViewData["Title"]</h2>
        <div class="no-print">
            <button onclick="window.print()" class="btn btn-primary me-2">
                <i class="bi bi-printer me-1"></i> Imprimir
            </button>
            <a asp-action="Index" class="btn btn-secondary">
                <i class="bi bi-arrow-left"></i> Volver
            </a>
        </div>
    </div>

    <div class="card shadow mb-4 no-print">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Filtros de Reporte</h6>
        </div>
        <div class="card-body">
            <form method="get" class="row g-3 align-items-end">
                <div class="col-md-4">
                    <label class="form-label">Colaborador</label>
                    <div class="input-group">
                        <input type="hidden" id="colaboradorId" name="colaboradorId" value="@selectedColaboradorId" />
                        <input type="text" id="colaboradorNombre" class="form-control" 
                               value="@(selectedColaboradorId.HasValue && colaboradores.Any(c => c.Id == selectedColaboradorId) ? 
                                       $"{colaboradores.First(c => c.Id == selectedColaboradorId).Persona.Apellidos}, {colaboradores.First(c => c.Id == selectedColaboradorId).Persona.Nombres}" : "")" 
                               readonly placeholder="Seleccione un colaborador..." required />
                        <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#searchModal">
                            <i class="bi bi-search"></i>
                        </button>
                    </div>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Desde</label>
                    <input type="date" name="inicio" class="form-control" value="@inicio.ToString("yyyy-MM-dd")" />
                </div>
                <div class="col-md-3">
                    <label class="form-label">Hasta</label>
                    <input type="date" name="fin" class="form-control" value="@fin.ToString("yyyy-MM-dd")" />
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-file-earmark-text me-2"></i>Generar
                    </button>
                </div>
            </form>
        </div>
    </div>

    @if (selectedColaboradorId.HasValue)
    {
        var selectedColaborador = colaboradores.FirstOrDefault(c => c.Id == selectedColaboradorId);
        var stats = Model.GroupBy(a => a.Estado).ToDictionary(g => g.Key, g => g.Count());

        @if (selectedColaborador != null)
        {
            <div class="mb-4 p-3 border rounded bg-light print-header">
                <h4 class="mb-2 text-primary">@selectedColaborador.Persona.Apellidos, @selectedColaborador.Persona.Nombres</h4>
                <div class="row">
                    <div class="col-md-4">
                        <strong><i class="bi bi-briefcase me-1"></i>Cargo:</strong> @(selectedColaborador.Cargo?.Nombre ?? "Sin Cargo")
                    </div>
                    <div class="col-md-4">
                        <strong><i class="bi bi-card-heading me-1"></i>DUI:</strong> @selectedColaborador.Persona.Dui
                    </div>
                    <div class="col-md-4">
                        <strong><i class="bi bi-telephone me-1"></i>Tel:</strong> @selectedColaborador.Persona.Telefono
                    </div>
                </div>
            </div>
        }

        <div class="row mb-4 print-row">
            <div class="col-xl-3 col-md-6 mb-4 print-col">
                <div class="card border-left-primary shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Registros</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">@Model.Count()</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-calendar-check fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4 print-col">
                <div class="card border-left-success shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Presentes</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">@(stats.ContainsKey("PRESENTE") ? stats["PRESENTE"] : 0)</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-person-check fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4 print-col">
                <div class="card border-left-danger shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Ausentes</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">@(stats.ContainsKey("AUSENTE") ? stats["AUSENTE"] : 0)</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-person-x fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4 print-col">
                <div class="card border-left-warning shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Tardanzas</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">@(stats.ContainsKey("TARDANZA") ? stats["TARDANZA"] : 0)</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-clock-history fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card shadow mb-4">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>Fecha</th>
                                <th>Día</th>
                                <th>Estado</th>
                                <th>Observaciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var item in Model)
                            {
                                <tr>
                                    <td>@item.Fecha.ToString("dd/MM/yyyy")</td>
                                    <td class="text-capitalize">@item.Fecha.ToString("dddd")</td>
                                    <td>
                                        <span class="badge @(item.Estado == "PRESENTE" ? "bg-success" : item.Estado == "AUSENTE" ? "bg-danger" : "bg-warning")">
                                            @item.Estado
                                        </span>
                                    </td>
                                    <td>@item.Observaciones</td>
                                </tr>
                            }
                            @if (!Model.Any())
                            {
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">No se encontraron registros en este rango de fechas.</td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    }
    else
    {
        <div class="text-center py-5">
            <i class="bi bi-search fa-4x text-gray-300 mb-3"></i>
            <p class="text-muted">Seleccione un colaborador y un rango de fechas para generar el reporte.</p>
        </div>
    }
</div>

<!-- Search Modal -->
<div class="modal fade" id="searchModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Buscar Colaborador</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="input-group mb-3">
                    <input type="text" id="searchInput" class="form-control" placeholder="Escriba el nombre del colaborador..." autocomplete="off">
                    <button class="btn btn-outline-primary" type="button" id="btnSearch">Buscar</button>
                </div>
                <div class="list-group" id="searchResults">
                    <!-- Results will be populated here -->
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        $(document).ready(function() {
            const searchInput = document.getElementById('searchInput');
            const searchResults = document.getElementById('searchResults');
            const searchModal = new bootstrap.Modal(document.getElementById('searchModal'));
            let debounceTimer;

            searchInput.addEventListener('input', function() {
                clearTimeout(debounceTimer);
                debounceTimer = setTimeout(() => performSearch(this.value), 300);
            });

            document.getElementById('btnSearch').addEventListener('click', function() {
                performSearch(searchInput.value);
            });

            function performSearch(term) {
                if (term.length < 2) {
                    searchResults.innerHTML = '<div class="text-center text-muted p-3">Ingrese al menos 2 caracteres</div>';
                    return;
                }

                searchResults.innerHTML = '<div class="text-center p-3"><div class="spinner-border text-primary" role="status"></div></div>';

                fetch(`@Url.Action("SearchColaboradores")?term=${encodeURIComponent(term)}`)
                    .then(response => response.json())
                    .then(data => {
                        searchResults.innerHTML = '';
                        if (data.length === 0) {
                            searchResults.innerHTML = '<div class="text-center text-muted p-3">No se encontraron resultados</div>';
                            return;
                        }

                        data.forEach(item => {
                            const button = document.createElement('button');
                            button.className = 'list-group-item list-group-item-action';
                            button.innerHTML = item.text; // The text already contains Name (Cargo)
                            button.onclick = function() {
                                selectColaborador(item.id, item.text);
                            };
                            searchResults.appendChild(button);
                        });
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        searchResults.innerHTML = '<div class="text-center text-danger p-3">Error al buscar</div>';
                    });
            }

            function selectColaborador(id, name) {
                // Extract just the name part if needed, but the full text is fine for display
                // Format from DB is: Name (Cargo)
                document.getElementById('colaboradorId').value = id;
                document.getElementById('colaboradorNombre').value = name;
                
                // Close modal
                const modalEl = document.getElementById('searchModal');
                const modal = bootstrap.Modal.getInstance(modalEl);
                modal.hide();
            }
            
            // Focus input when modal opens
            document.getElementById('searchModal').addEventListener('shown.bs.modal', function () {
                searchInput.focus();
            });
        });
    </script>
}

@section Styles {
    <style>
        .border-left-primary { border-left: 0.25rem solid #4e73df !important; }
        .border-left-success { border-left: 0.25rem solid #1cc88a !important; }
        .border-left-danger { border-left: 0.25rem solid #e74a3b !important; }
        .border-left-warning { border-left: 0.25rem solid #f6c23e !important; }
        .text-xs { font-size: .7rem; }

        @@media print {
            .no-print { display: none !important; }
            .sidebar, .top-header, .footer { display: none !important; }
            .main-content { margin-left: 0 !important; padding: 0 !important; }
            .page-container { padding: 0 !important; }
            .card { border: 1px solid #ddd !important; box-shadow: none !important; }
            .card-body { padding: 1rem !important; }
            body { background: white !important; }
            .container-fluid { width: 100% !important; padding: 0 !important; }
            
            /* Force row layout for cards */
            .print-row {
                display: flex !important;
                flex-wrap: nowrap !important;
                gap: 10px;
            }
            .print-col {
                flex: 0 0 25% !important;
                max-width: 25% !important;
                margin-bottom: 0 !important;
            }
            
            /* Header styling */
            .print-header {
                background-color: #f8f9fa !important;
                border: 1px solid #dee2e6 !important;
                padding: 15px !important;
                margin-bottom: 20px !important;
            }
            .print-header h4 {
                color: #000 !important;
                margin-bottom: 10px !important;
            }
        }
    </style>
}
