@model foundation_system.Models.ViewModels.RegistroGastoViewModel

@{
    ViewData["Title"] = "Registrar Gasto";
}

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800">@ViewData["Title"]</h1>
        <a asp-controller="CajaChica" asp-action="Details" asp-route-id="@Model.CajaChicaId" class="btn btn-secondary">
            <i class="bi bi-arrow-left me-1"></i> Volver
        </a>
    </div>

    <div class="row">
        <div class="col-md-8">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold text-primary">Detalles del Gasto</h6>
                    <span class="badge bg-success">Saldo Disponible: @Model.SaldoDisponible.ToString("C")</span>
                </div>
                <div class="card-body">
                    <form asp-action="CreateGasto">
                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                        <input type="hidden" asp-for="CajaChicaId" />
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label asp-for="Fecha" class="form-label">Fecha</label>
                                <input asp-for="Fecha" class="form-control" type="date" />
                                <span asp-validation-for="Fecha" class="text-danger"></span>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label asp-for="Monto" class="form-label">Monto ($)</label>
                                <div class="input-group">
                                    <span class="input-group-text">$</span>
                                    <input asp-for="Monto" class="form-control" type="number" step="0.01" min="0.01" max="@Model.SaldoDisponible" />
                                </div>
                                <span asp-validation-for="Monto" class="text-danger"></span>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label asp-for="CategoriaId" class="form-label">Categoría</label>
                            <select asp-for="CategoriaId" class="form-select" asp-items="ViewBag.CategoriaId">
                                <option value="">-- Seleccione una Categoría --</option>
                            </select>
                            <span asp-validation-for="CategoriaId" class="text-danger"></span>
                        </div>
                        
                        <div class="mb-3">
                            <label asp-for="ProveedorId" class="form-label">Proveedor (Opcional)</label>
                            <div class="input-group">
                                <input type="hidden" asp-for="ProveedorId" id="ProveedorId" />
                                <input type="text" id="ProveedorDisplay" class="form-control" placeholder="Buscar proveedor..." readonly />
                                <button class="btn btn-outline-secondary" type="button" data-bs-toggle="modal" data-bs-target="#searchModal">
                                    <i class="bi bi-search"></i> Buscar
                                </button>
                                <button class="btn btn-outline-danger" type="button" id="btnClearProveedor" title="Limpiar selección">
                                    <i class="bi bi-x"></i>
                                </button>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label asp-for="Descripcion" class="form-label">Descripción / Concepto</label>
                            <textarea asp-for="Descripcion" class="form-control" rows="3"></textarea>
                            <span asp-validation-for="Descripcion" class="text-danger"></span>
                        </div>

                        <div class="d-grid">
                            <button type="submit" class="btn btn-danger">
                                <i class="bi bi-dash-circle me-2"></i> Registrar Gasto
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </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 Proveedor</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 o NIT del proveedor..." 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 {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    
    <script>
        $(document).ready(function() {
            let searchTimeout;

            // Search function
            function performSearch() {
                const term = $('#searchInput').val();
                if (term.length < 2) return;

                $('#searchResults').html('<div class="text-center p-3"><div class="spinner-border text-primary" role="status"></div></div>');

                $.get('@Url.Action("SearchProveedores", "MovimientoCaja")', { term: term })
                    .done(function(data) {
                        $('#searchResults').empty();
                        if (data.length === 0) {
                            $('#searchResults').append('<div class="list-group-item text-muted">No se encontraron resultados</div>');
                        } else {
                            data.forEach(function(item) {
                                const btn = $('<button type="button" class="list-group-item list-group-item-action"></button>')
                                    .text(item.text)
                                    .click(function() {
                                        $('#ProveedorId').val(item.id);
                                        $('#ProveedorDisplay').val(item.text);
                                        $('#searchModal').modal('hide');
                                    });
                                $('#searchResults').append(btn);
                            });
                        }
                    })
                    .fail(function() {
                        $('#searchResults').html('<div class="list-group-item text-danger">Error al buscar proveedores</div>');
                    });
            }

            // Event listeners
            $('#btnSearch').click(performSearch);

            $('#searchInput').on('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(performSearch, 500);
            });
            
            $('#btnClearProveedor').click(function() {
                $('#ProveedorId').val('');
                $('#ProveedorDisplay').val('');
            });

            // Focus input when modal opens
            $('#searchModal').on('shown.bs.modal', function () {
                $('#searchInput').focus();
            });
        });
    </script>
}
