@page "/sales/personform"
@page "/sales/personform/{PersonId:int}"

@using System.ComponentModel.DataAnnotations
@using phronCare.UIBlazor.Services.Sales
@using phronCare.UIBlazor.Shared.Modals

@inject BusinessUnitService businessUnitService
@inject NavigationManager Navigation
@inject PeopleService peopleService
@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">Información de la Persona</h3>
    </div>

    <div class="card-body">
        <EditForm Model="@person" OnValidSubmit="@HandleValidSubmit">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <div class="row">
                <div class="col-md-6">
                    <label for="Name">Nombre completo:</label>
                    <InputText id="Name" @bind-Value="person.Name" class="form-control" />
                </div>
                <div class="col-md-6">
                    <label for="Phone">Teléfono:</label>
                    <InputText id="Phone" @bind-Value="person.Phone" class="form-control" />
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <label for="Email">Email:</label>
                    <InputText id="Email" @bind-Value="person.Email" class="form-control" />
                </div>
                <div class="col-md-6">
                    <label for="DefaultCommissionPercent">Porcentaje Comisión (%):</label>
                    <InputNumber id="DefaultCommissionPercent" @bind-Value="person.DefaultCommissionPercent" class="form-control" step="0.01" />
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <label for="BusinessunitsId">Unidad de Negocio:</label>
                    <InputSelect id="BusinessunitsId" @bind-Value="person.BusinessunitsId" class="form-control">
                        <option value="">-- Seleccionar --</option>
                        @foreach (var unit in businessUnits)
                        {
                            <option value="@unit.Id">@unit.Description</option>
                        }
                    </InputSelect>
                </div>
                <div class="col-md-6">
                    <label for="PeoplegroupsId">Grupo Comercial (opcional):</label>
                    <InputSelect id="PeoplegroupsId" @bind-Value="person.PeoplegroupsId" class="form-control">
                        <option value="">-- Seleccionar --</option>
                        @foreach (var group in peopleGroups)
                        {
                            <option value="@group.Id">@group.Name</option>
                        }
                    </InputSelect>
                </div>
            </div>

            <div class="row mt-3">
                <div class="col-md-6 d-flex align-items-center justify-content-start">
                    <div class="form-check form-switch">
                        <InputCheckbox id="Active" @bind-Value="person.Active" class="form-check-input" />
                        <label class="form-check-label ms-2" for="Active">Activo</label>
                    </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 Persona")
            </button>
            <button type="button" class="btn btn-secondary" @onclick="Cancel">Cancelar</button>
        </div>
    </div>
</div>

@code {
    [Parameter]
    public int? PersonId { get; set; }

    private EPerson person { get; set; } = new();
    private bool isSaving = false;
    private string returnUrl = "/sales/people";

    private List<EBusinessUnit> businessUnits = new();
    private List<EPeopleGroup> peopleGroups = new();

    protected override async Task OnInitializedAsync()
    {
        await LoadBusinessUnits();
        await LoadPeopleGroups();

        if (PersonId.HasValue)
        {
            person = await peopleService.GetPersonByIdAsync(PersonId.Value) ?? new();
        }
    }

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

        if (result.Cancelled)
            return;

        try
        {
            isSaving = true;

            if (PersonId.HasValue)
            {
                await peopleService.UpdatePersonAsync(person);
            }
            else
            {
                await peopleService.CreatePersonAsync(person);
            }

            toastService.ShowSuccess("Persona guardada exitosamente.");
            Navigation.NavigateTo(returnUrl);
        }
        catch (Exception ex)
        {
            toastService.ShowError($"Error: {ex.Message}");
        }
        finally
        {
            isSaving = false;
        }
    }

    private void Cancel()
    {
        Navigation.NavigateTo(returnUrl);
    }

    private async Task LoadBusinessUnits()
    {
        businessUnits = await businessUnitService.GetAllAsync();
    }

    private async Task LoadPeopleGroups()
    {
        // Simulamos carga de Grupos Comerciales. Debería venir de un servicio real.
        peopleGroups = new List<EPeopleGroup>
        {
            new EPeopleGroup { Id = 1, Name = "Grupo 1" },
            new EPeopleGroup { Id = 2, Name = "Grupo 2" },
        };
    }
}
