@page "/admin/spa/therapists"
@layout AdminLayout
@inherits AdminBase
@inject PosDataService DataService
@inject IDialogService DialogService
@inject ISnackbar Snackbar
@using WebClientTpos.Client.Services
@using MudBlazor

@*
    EN: Therapist Management page — CRUD for spa/beauty therapists with specialties and status.
    VI: Trang quan ly nhan vien tri lieu — CRUD cho nhan vien spa/beauty voi chuyen mon va trang thai.
*@

<PageTitle>Quan ly nhan vien — aPOS POS</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">Quan ly nhan vien</h1>
        <p class="admin-topbar__subtitle">Danh sach nhan vien tri lieu, chuyen mon va trang thai</p>
    </div>
    <div class="admin-topbar__right" style="display:flex;align-items:center;gap:12px;">
        <div style="position:relative;">
            <i data-lucide="search" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
            <input type="text" @bind="_searchQuery" @bind:event="oninput"
                   placeholder="Tim theo ten..."
                   style="padding:8px 12px 8px 36px;border-radius:10px;border:1px solid var(--admin-border);background:var(--admin-bg-interactive);color:var(--admin-text-primary);font-size:13px;width:220px;outline:none;" />
        </div>
        <MudButton Variant="Variant.Filled"
                   Color="Color.Primary"
                   OnClick="OpenCreateDialog"
                   StartIcon="@Icons.Material.Filled.PersonAdd">
            Them nhan vien
        </MudButton>
    </div>
</div>

@* ═══ CONTENT ═══ *@
<div class="admin-content">
    @if (_loading)
    {
        <div style="display:flex;justify-content:center;padding:48px;">
            <MudProgressCircular Size="Size.Large" Indeterminate="true" Color="Color.Primary" />
        </div>
    }
    else if (!FilteredTherapists.Any())
    {
        <MudAlert Severity="Severity.Info" Variant="Variant.Outlined" Class="mb-4">
            @if (string.IsNullOrWhiteSpace(_searchQuery))
            {
                <span>Chua co nhan vien nao. Nhan "Them nhan vien" de bat dau.</span>
            }
            else
            {
                <span>Khong tim thay nhan vien nao phu hop voi "@_searchQuery".</span>
            }
        </MudAlert>
    }
    else
    {
        <div class="admin-panel">
            <div class="admin-panel__body" style="padding:0;">
                <MudTable Items="@FilteredTherapists"
                          Dense="true"
                          Hover="true"
                          Striped="true"
                          Elevation="0"
                          Class="mud-table-dark">
                    <HeaderContent>
                        <MudTh Style="font-weight:700;">Ten</MudTh>
                        <MudTh Style="font-weight:700;">Chuyen mon</MudTh>
                        <MudTh Style="font-weight:700;">Lien he</MudTh>
                        <MudTh Style="font-weight:700;">Trang thai</MudTh>
                        <MudTh Style="font-weight:700;text-align:right;">Thao tac</MudTh>
                    </HeaderContent>
                    <RowTemplate>
                        <MudTd>
                            <div style="display:flex;align-items:center;gap:10px;">
                                <div style="width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg, #FF5C00 0%, #FF8A3D 100%);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:#fff;flex-shrink:0;">
                                    @GetInitials(context.Name)
                                </div>
                                <span style="font-weight:600;">@context.Name</span>
                            </div>
                        </MudTd>
                        <MudTd>
                            <div style="display:flex;flex-wrap:wrap;gap:4px;">
                                @if (context.Specialties != null)
                                {
                                    @foreach (var s in context.Specialties)
                                    {
                                        <MudChip T="string"
                                                 Size="Size.Small"
                                                 Color="Color.Primary"
                                                 Variant="Variant.Outlined"
                                                 Style="font-size:11px;">@s</MudChip>
                                    }
                                }
                            </div>
                        </MudTd>
                        <MudTd>
                            <div style="font-size:12px;color:var(--admin-text-secondary);">
                                @if (!string.IsNullOrEmpty(context.Phone))
                                {
                                    <div>@context.Phone</div>
                                }
                                @if (!string.IsNullOrEmpty(context.Email))
                                {
                                    <div>@context.Email</div>
                                }
                            </div>
                        </MudTd>
                        <MudTd>
                            @if (context.IsActive)
                            {
                                <MudChip T="string" Size="Size.Small" Color="Color.Success" Variant="Variant.Filled"
                                         Style="font-size:11px;">Hoat dong</MudChip>
                            }
                            else
                            {
                                <MudChip T="string" Size="Size.Small" Color="Color.Default" Variant="Variant.Filled"
                                         Style="font-size:11px;">Ngung hoat dong</MudChip>
                            }
                        </MudTd>
                        <MudTd Style="text-align:right;">
                            <MudIconButton Icon="@Icons.Material.Filled.Edit"
                                           Size="Size.Small"
                                           Color="Color.Primary"
                                           OnClick="@(() => OpenEditDialog(context))"
                                           Title="Chinh sua" />
                            @if (context.IsActive)
                            {
                                <MudIconButton Icon="@Icons.Material.Filled.PersonOff"
                                               Size="Size.Small"
                                               Color="Color.Error"
                                               OnClick="@(() => ConfirmDeactivate(context))"
                                               Title="Vo hieu hoa" />
                            }
                        </MudTd>
                    </RowTemplate>
                </MudTable>
            </div>
        </div>
    }
</div>

@* ═══ CREATE/EDIT DIALOG ═══ *@
<MudDialog @bind-Visible="_dialogVisible" Options="_dialogOptions">
    <TitleContent>
        <MudText Typo="Typo.h6">@(_editingId.HasValue ? "Chinh sua nhan vien" : "Them nhan vien moi")</MudText>
    </TitleContent>
    <DialogContent>
        <MudForm @ref="_form">
            <MudTextField @bind-Value="_formName"
                          Label="Ten nhan vien"
                          Required="true"
                          RequiredError="Vui long nhap ten nhan vien"
                          Variant="Variant.Outlined"
                          Class="mb-3" />

            <MudTextField @bind-Value="_formPhone"
                          Label="So dien thoai"
                          Variant="Variant.Outlined"
                          Class="mb-3" />

            <MudTextField @bind-Value="_formEmail"
                          Label="Email"
                          Variant="Variant.Outlined"
                          Class="mb-3" />

            <MudText Typo="Typo.body2" Class="mb-2" Style="color:var(--admin-text-secondary);">Chuyen mon</MudText>
            <MudChipSet T="string" @bind-SelectedValues="_selectedSpecialties" SelectionMode="SelectionMode.MultiSelection" Color="Color.Primary" Variant="Variant.Outlined" Class="mb-3">
                @foreach (var spec in _availableSpecialties)
                {
                    <MudChip T="string" Value="@spec">@spec</MudChip>
                }
            </MudChipSet>

            <MudTextField @bind-Value="_formCustomSpecialty"
                          Label="Chuyen mon khac (nhap va nhan Enter)"
                          Variant="Variant.Outlined"
                          Adornment="Adornment.End"
                          AdornmentIcon="@Icons.Material.Filled.Add"
                          OnAdornmentClick="AddCustomSpecialty"
                          OnKeyUp="OnSpecialtyKeyUp"
                          Class="mb-3" />

            <MudTextField @bind-Value="_formWorkingHours"
                          Label="Gio lam viec (vd: 08:00 - 17:00)"
                          Variant="Variant.Outlined"
                          Class="mb-3" />
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="CloseDialog" Variant="Variant.Text">Huy</MudButton>
        <MudButton OnClick="SaveTherapistAsync"
                   Variant="Variant.Filled"
                   Color="Color.Primary"
                   Disabled="_saving">
            @if (_saving)
            {
                <MudProgressCircular Size="Size.Small" Indeterminate="true" Color="Color.Surface" Class="mr-2" />
            }
            @(_editingId.HasValue ? "Cap nhat" : "Tao moi")
        </MudButton>
    </DialogActions>
</MudDialog>

@code {
    // EN: State fields / VI: Cac truong trang thai
    private bool _loading = true;
    private bool _saving = false;
    private List<PosDataService.TherapistInfo> _therapists = new();
    private string _searchQuery = string.Empty;

    // EN: Dialog state / VI: Trang thai dialog
    private bool _dialogVisible = false;
    private MudForm? _form;
    private Guid? _editingId;
    private string _formName = string.Empty;
    private string _formPhone = string.Empty;
    private string _formEmail = string.Empty;
    private string _formWorkingHours = string.Empty;
    private string _formCustomSpecialty = string.Empty;
    private IReadOnlyCollection<string> _selectedSpecialties = new List<string>();

    private static readonly DialogOptions _dialogOptions = new()
    {
        MaxWidth = MaxWidth.Small,
        FullWidth = true,
        CloseOnEscapeKey = true
    };

    // EN: Common spa specialties / VI: Cac chuyen mon spa pho bien
    private static readonly string[] _availableSpecialties = new[]
    {
        "Massage", "Facial", "Body Scrub", "Nail Art", "Hair Styling",
        "Waxing", "Aromatherapy", "Hot Stone", "Acupuncture", "Skin Care"
    };

    // EN: Filtered therapist list based on search query
    // VI: Danh sach nhan vien da loc theo tu khoa tim kiem
    private IEnumerable<PosDataService.TherapistInfo> FilteredTherapists =>
        string.IsNullOrWhiteSpace(_searchQuery)
            ? _therapists
            : _therapists.Where(t => t.Name.Contains(_searchQuery, StringComparison.OrdinalIgnoreCase));

    /// <summary>
    /// EN: Get the current shop ID from query string.
    /// VI: Lay shop ID tu query string.
    /// </summary>
    private Guid? GetCurrentShopId()
    {
        var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
        var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
        if (Guid.TryParse(query["shopId"], out var qsShopId))
            return qsShopId;
        return null;
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await LoadTherapistsAsync();
    }

    /// <summary>
    /// EN: Load therapists from API.
    /// VI: Tai danh sach nhan vien tu API.
    /// </summary>
    private async Task LoadTherapistsAsync()
    {
        var shopId = GetCurrentShopId();
        if (!shopId.HasValue)
        {
            Snackbar.Add("Vui long chon shop truoc.", Severity.Warning);
            _loading = false;
            return;
        }

        _loading = true;
        StateHasChanged();

        try
        {
            _therapists = await DataService.GetTherapistsAsync(shopId.Value);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Loi tai danh sach: {ex.Message}", Severity.Error);
            _therapists = new();
        }
        finally
        {
            _loading = false;
            StateHasChanged();
        }
    }

    // ═══ DIALOG METHODS ═══

    private void OpenCreateDialog()
    {
        _editingId = null;
        _formName = string.Empty;
        _formPhone = string.Empty;
        _formEmail = string.Empty;
        _formWorkingHours = string.Empty;
        _formCustomSpecialty = string.Empty;
        _selectedSpecialties = new List<string>();
        _dialogVisible = true;
    }

    private void OpenEditDialog(PosDataService.TherapistInfo therapist)
    {
        _editingId = therapist.Id;
        _formName = therapist.Name;
        _formPhone = therapist.Phone ?? string.Empty;
        _formEmail = therapist.Email ?? string.Empty;
        _formWorkingHours = therapist.WorkingHours ?? string.Empty;
        _formCustomSpecialty = string.Empty;
        _selectedSpecialties = therapist.Specialties?.ToList() ?? new List<string>();
        _dialogVisible = true;
    }

    private void CloseDialog()
    {
        _dialogVisible = false;
    }

    private void AddCustomSpecialty()
    {
        if (!string.IsNullOrWhiteSpace(_formCustomSpecialty))
        {
            var current = _selectedSpecialties.ToList();
            var trimmed = _formCustomSpecialty.Trim();
            if (!current.Contains(trimmed))
            {
                current.Add(trimmed);
                _selectedSpecialties = current;
            }
            _formCustomSpecialty = string.Empty;
        }
    }

    private void OnSpecialtyKeyUp(KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
            AddCustomSpecialty();
    }

    /// <summary>
    /// EN: Save therapist (create or update).
    /// VI: Luu nhan vien (tao moi hoac cap nhat).
    /// </summary>
    private async Task SaveTherapistAsync()
    {
        if (_form != null)
        {
            await _form.Validate();
            if (!_form.IsValid) return;
        }

        if (string.IsNullOrWhiteSpace(_formName))
        {
            Snackbar.Add("Vui long nhap ten nhan vien.", Severity.Warning);
            return;
        }

        var shopId = GetCurrentShopId();
        if (!shopId.HasValue)
        {
            Snackbar.Add("Vui long chon shop truoc.", Severity.Warning);
            return;
        }

        _saving = true;
        StateHasChanged();

        try
        {
            var specialties = _selectedSpecialties.ToArray();
            var req = new PosDataService.CreateTherapistRequest(
                shopId.Value,
                _formName.Trim(),
                specialties.Length > 0 ? specialties : null,
                string.IsNullOrWhiteSpace(_formPhone) ? null : _formPhone.Trim(),
                string.IsNullOrWhiteSpace(_formEmail) ? null : _formEmail.Trim(),
                string.IsNullOrWhiteSpace(_formWorkingHours) ? null : _formWorkingHours.Trim()
            );

            bool success;
            if (_editingId.HasValue)
            {
                success = await DataService.UpdateTherapistAsync(_editingId.Value, req);
            }
            else
            {
                success = await DataService.CreateTherapistAsync(req);
            }

            if (success)
            {
                Snackbar.Add(_editingId.HasValue ? "Da cap nhat nhan vien." : "Da them nhan vien moi.", Severity.Success);
                CloseDialog();
                await LoadTherapistsAsync();
            }
            else
            {
                Snackbar.Add("Thao tac that bai. Vui long thu lai.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Loi: {ex.Message}", Severity.Error);
        }
        finally
        {
            _saving = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// EN: Confirm and deactivate a therapist.
    /// VI: Xac nhan va vo hieu hoa nhan vien.
    /// </summary>
    private async Task ConfirmDeactivate(PosDataService.TherapistInfo therapist)
    {
        var confirmed = await DialogService.ShowMessageBox(
            "Vo hieu hoa nhan vien",
            $"Ban co chac chan muon vo hieu hoa nhan vien '{therapist.Name}'? Nhan vien se khong nhan lich hen moi.",
            yesText: "Vo hieu hoa",
            cancelText: "Huy");

        if (confirmed != true) return;

        try
        {
            var success = await DataService.DeactivateTherapistAsync(therapist.Id);
            if (success)
            {
                Snackbar.Add($"Da vo hieu hoa nhan vien '{therapist.Name}'.", Severity.Success);
                await LoadTherapistsAsync();
            }
            else
            {
                Snackbar.Add("Vo hieu hoa that bai. Vui long thu lai.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Loi: {ex.Message}", Severity.Error);
        }
    }

    private static string GetInitials(string name)
    {
        if (string.IsNullOrWhiteSpace(name)) return "??";
        var parts = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length >= 2)
            return $"{parts[0][0]}{parts[^1][0]}".ToUpper();
        return name[..Math.Min(2, name.Length)].ToUpper();
    }
}
