@page "/sales/institutionform"
@page "/sales/institutionform/{InstitutionId:int?}"
@using System.ComponentModel.DataAnnotations
@using phronCare.UIBlazor.Services.Sales
@using phronCare.UIBlazor.Shared.Modals

@inject InstitutionService institutionService
@inject NavigationManager Navigation
@inject IToastService ToastService
@inject IModalService Modal

<div class="card" style="zoom:80%">
    <div class="card-header d-flex justify-content-center align-items-center">
        <h3 class="card-title m-0">@((InstitutionId.HasValue ? "Editar institución" : "Nueva institución"))</h3>
    </div>
    <div class="card-body">
        <EditForm Model="_model">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <!-- Fila 1: Nombre de la institución -->
            <div class="row mb-3">
                <div class="col-md-8">
                    <label for="Name">Nombre:</label>
                    <InputText id="Name" @bind-Value="_model.Name" class="form-control" />
                    <ValidationMessage For="@(() => _model.Name)" />
                </div>
                <div class="col-md-4">
                    <label for="Type">Tipo de institución:</label>
                    <InputSelect id="Type" @bind-Value="_model.Type" class="form-control">
                        <option value="">--- Seleccionar ---</option>
                        @foreach (var type in InstitutionTypes)
                        {
                            <option value="@type.Code">@type.Description</option>
                        }
                    </InputSelect>
                    <ValidationMessage For="@(() => _model.Type)" />
                </div>
            </div>


            <!-- Fila 3: Dirección -->
            <div class="row mb-3">
                <div class="col-md-12">
                    <label for="Streetaddress">Dirección:</label>
                    <InputText id="Streetaddress" @bind-Value="_model.Streetaddress" class="form-control" />
                    <ValidationMessage For="@(() => _model.Streetaddress)" />
                </div>
            </div>

            <!-- Fila 4: Ciudad, Provincia, Teléfono -->
            <div class="row mb-3">
                <div class="col-md-4">
                    <label for="City">Ciudad:</label>
                    <InputText id="City" @bind-Value="_model.City" class="form-control" />
                    <ValidationMessage For="@(() => _model.City)" />
                </div>
                <div class="col-md-4">
                    <label for="Province">Provincia:</label>
                    <InputSelect id="Province" @bind-Value="_model.Province" class="form-control">
                        <option value="">--- Seleccionar ---</option>
                        @foreach (var province in provinces)
                        {
                            <option value="@province">@province</option>
                        }
                    </InputSelect>
                    <ValidationMessage For="@(() => _model.Province)" />
                </div>
                <div class="col-md-4">
                    <label for="Phone">Teléfono:</label>
                    <InputText id="Phone" @bind-Value="_model.Phone" class="form-control" />
                    <ValidationMessage For="@(() => _model.Phone)" />
                </div>
            </div>
            <!-- Fila 7: Mapas - Ubicación -->
            <div class="row mb-3">
                <div class="row">
                    <!-- Columna izquierda: campos Latitud y Longitud -->
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="Email">Email:</label>
                            <InputText id="Email" @bind-Value="_model.Email" class="form-control" />
                            <ValidationMessage For="@(() => _model.Email)" />
                        </div>

                        <div class="mb-3">
                            <label for="Operatingroominfo">Información sobre quirófanos:</label>
                            <InputTextArea id="Operatingroominfo" @bind-Value="_model.Operatingroominfo" class="form-control" rows="3" />
                            <ValidationMessage For="@(() => _model.Operatingroominfo)" />
                        </div>
                        <div class="mb-3">
                            <label for="Latitude" class="form-label">Latitud</label>
                            <InputNumber @bind-Value="_model.Latitude" class="form-control" id="Latitude" />
                        </div>
                        <div class="mb-3">
                            <label for="Longitude" class="form-label">Longitud</label>
                            <InputNumber @bind-Value="_model.Longitude" class="form-control" id="Longitude" />
                        </div>
                    </div>

                    <!-- Columna derecha: mapa -->
                    <div class="col-md-6" style="zoom:80%">
                        @if (_model.Latitude.HasValue && _model.Longitude.HasValue)
                        {
                            <PhMap Latitude="@_model.Latitude.Value"
                                   Longitude="@_model.Longitude.Value"
                                   Zoom="13"
                                   OnLocationChanged="HandleLocationChanged" />
                        }
                        else
                        {
                            <div class="text-muted">Ingrese coordenadas para visualizar el mapa</div>
                        }
                    </div>
                </div>

            </div>
        </EditForm>
    </div>
    <div class="card-footer">
        <div class="d-flex justify-content-end align-items-center py-3">
            <button class="btn btn-primary me-2" type="button" @onclick="HandleValidSubmit" disabled="@isSaving"> @(isSaving ? "Guardando..." : "Guardar institución") </button>
            <button type="button" class="btn btn-secondary" @onclick="NavigateBack">Cancelar</button>
        </div>
    </div>
</div>

@code {
    [Parameter] public int? InstitutionId { get; set; }
    [Parameter] public string? returnUrl { get; set; } = "/sales/institutions";
    private string searchQuery = string.Empty;

    private EInstitution _model = new();
    private bool isSaving = false;
    private List<string> provinces = new()
    {
        "Buenos Aires", "CABA", "Catamarca", "Chaco", "Chubut", "Córdoba", "Corrientes",
        "Entre Ríos", "Formosa", "Jujuy", "La Pampa", "La Rioja", "Mendoza", "Misiones",
        "Neuquén", "Río Negro", "Salta", "San Juan", "San Luis", "Santa Cruz",
        "Santa Fe", "Santiago del Estero", "Tierra del Fuego", "Tucumán"
    };

    private List<(string Code, string Description)> InstitutionTypes = new()
    {
        ("ESCIG", "Establecimiento de salud con internación general"),
        ("ESCIEP", "Internación especializada en pediatría"),
        ("ESCIEM", "Internación especializada en maternidad/materno infantil"),
        ("ESCIESM", "Internación especializada en salud mental"),
        ("ESCIE", "Internación especializada en otras especialidades"),
        ("ESCIRES", "Establecimientos Residenciales"),
        ("ESSIDT", "Ambulatorio diagnóstico y tratamiento"),
        ("ESSID", "Ambulatorio diagnóstico"),
        ("ESSIT", "Ambulatorio tratamiento"),
        ("ESCL", "Establecimiento complementario"),
        ("ESIAIS", "Ambulatorios de inclusión social")
    };
    protected override async Task OnInitializedAsync()
    {
        if (InstitutionId.HasValue)
        {
            _model = await institutionService.GetByIdAsync(InstitutionId.Value);
        }
    }

    private async Task HandleLocationChanged((double lat, double lng) location)
    {
        _model.Latitude = location.lat;
        _model.Longitude = location.lng;
    }

    private async Task HandleValidSubmit()
    {
        var parameters = new ModalParameters();
        parameters.Add("Message", "¿Desea guardar los cambios de la institución?");
        var modal = Modal.Show<ConfirmModal>("Confirmación", parameters);
        var result = await modal.Result;

        if (result.Cancelled)
            return;

        try
        {
            HttpResponseMessage response;

            if (_model.Id == 0)
                response = await institutionService.CreateAsync(_model);
            else
                response = await institutionService.UpdateAsync(_model);

            if (response.IsSuccessStatusCode)
            {
                ToastService.ShowSuccess("Institución guardada correctamente.");
                NavigateBack();
            }
            else
            {
                var error = await response.Content.ReadAsStringAsync();
                ToastService.ShowError($"Error: {error}");
            }
        }
        catch (Exception ex)
        {
            ToastService.ShowError($"Error: {ex.Message}");
        }
    }

    private void NavigateBack()
    {
        Navigation.NavigateTo(returnUrl ?? "/sales/institutions");
    }
}
