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

@inject DocumentTypeService documentTypeService
@inject PatientService patientService
@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">@((PatientId.HasValue ? "Editar paciente" : "Nuevo paciente"))</h3>
    </div>
    <div class="card-body">
        <EditForm Model="_model" OnValidSubmit="HandleValidSubmit">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <!-- Fila 1: Nombre y Apellido -->
            <div class="row mb-3">
                <div class="col-md-6">
                    <label for="FirstName">Nombre:</label>
                    <InputText id="FirstName" @bind-Value="_model.Firstname" class="form-control" />
                    <ValidationMessage For="@(() => _model.Firstname)" />
                </div>
                <div class="col-md-6">
                    <label for="LastName">Apellido:</label>
                    <InputText id="LastName" @bind-Value="_model.Lastname" class="form-control" />
                    <ValidationMessage For="@(() => _model.Lastname)" />
                </div>
            </div>

            <!-- Fila 2: Tipo Doc, Nro Doc, Afiliado -->
            <div class="row mb-3">
                <div class="col-md-4">
                    <label for="DocumentType">Tipo de documento:</label>
                    <InputSelect id="DocumentType" @bind-Value="_model.DocumenttypesId" class="form-control">
                        <option value="">Seleccione un tipo</option>
                        @foreach (var type in documentTypes)
                        {
                            <option value="@type.Id">@type.Description</option>
                        }
                    </InputSelect>
                    <ValidationMessage For="@(() => _model.DocumenttypesId)" />
                </div>
                <div class="col-md-4">
                    <label for="DocumentNumber">Número de documento:</label>
                    <InputText id="DocumentNumber" @bind-Value="_model.DocumentNumber" class="form-control" />
                    <ValidationMessage For="@(() => _model.DocumentNumber)" />
                </div>
                <div class="col-md-4">
                    <label for="AffiliateNumber">Número de afiliado:</label>
                    <InputText id="AffiliateNumber" @bind-Value="_model.AffiliateNumber" class="form-control" />
                    <ValidationMessage For="@(() => _model.AffiliateNumber)" />
                </div>
            </div>

            <!-- Fila 3: Fecha de nacimiento, Género -->
            <div class="row mb-3">
                <div class="col-md-4">
                    <label for="Birthdate">Fecha de nacimiento:</label>
                    <InputDate id="Birthdate" @bind-Value="_model.Birthdate" class="form-control" />
                    <ValidationMessage For="@(() => _model.Birthdate)" />
                </div>
                <div class="col-md-4">
                    <label for="Gender">Género:</label>
                    <InputSelect id="Gender" @bind-Value="_model.Gender" class="form-control">
                        <option value="">Seleccione</option>
                        <option value="Femenino">Femenino</option>
                        <option value="Masculino">Masculino</option>
                        <option value="Otro">Otro</option>
                        <option value="Prefiero no decir">Prefiero no decir</option>
                    </InputSelect>
                    <ValidationMessage For="@(() => _model.Gender)" />
                </div>
            </div>

            <!-- Fila 4: Teléfono, Email -->
            <div class="row mb-3">
                <div class="col-md-6">
                    <label for="Phone">Teléfono:</label>
                    <InputText id="Phone" @bind-Value="_model.Phone" class="form-control" />
                    <ValidationMessage For="@(() => _model.Phone)" />
                </div>
                <div class="col-md-6">
                    <label for="Email">Email:</label>
                    <InputText id="Email" @bind-Value="_model.Email" class="form-control" />
                    <ValidationMessage For="@(() => _model.Email)" />
                </div>
            </div>

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

            <!-- Fila 6: Notas -->
            <div class="row mb-3">
                <div class="col-12">
                    <label for="Notes">Notas:</label>
                    <InputTextArea id="Notes" @bind-Value="_model.Notes" class="form-control" rows="3" />
                    <ValidationMessage For="@(() => _model.Notes)" />
                </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 paciente") </button>
            <button type="button" class="btn btn-secondary" @onclick="NavigateBack">Cancelar</button>
        </div>
    </div>

</div>

@code {
    [Parameter] public int? PatientId { get; set; }
    [Parameter] public string? returnUrl { get; set; } = "/sales/patients";

    private EPatient _model = new();
    private List<EDocumentType> documentTypes = new();
    private bool isSaving = false;

    protected override async Task OnInitializedAsync()
    {
        await LoadDocumentTypes();

        if (PatientId.HasValue)
        {
            _model = await patientService.GetByIdAsync(PatientId.Value);
        }
    }
    private async Task LoadDocumentTypes()
    {
        documentTypes = await documentTypeService.GetAllAsync();
    }
    private async Task HandleValidSubmit()
    {
        var parameters = new ModalParameters();
        parameters.Add("Message", "¿Desea guardar los cambios del paciente?");
        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 patientService.CreateAsync(_model);
            else
                response = await patientService.UpdateAsync(_model);

            if (response.IsSuccessStatusCode)
            {
                ToastService.ShowSuccess("Paciente guardado 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/patients");
    }
}
