@*
    EN: Therapist management component — CRUD for spa/beauty therapists embedded in ShopPage.
    VI: Component quan ly nhan vien tri lieu — CRUD cho nhan vien spa/beauty nhung trong ShopPage.
*@
@using WebClientTpos.Client.Services
@using MudBlazor
@inject PosDataService DataService
@inject IDialogService DialogService
@inject ISnackbar Snackbar

@* ═══ TOP ACTIONS ═══ *@
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
    <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>
    <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick="OpenCreateDialog">
        <i data-lucide="user-plus" style="width:16px;height:16px;"></i>Them nhan vien
    </button>
</div>

@* ═══ TABLE ═══ *@
@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())
{
    <div class="admin-panel">
        <div class="admin-panel__body" style="text-align:center;padding:40px 20px;">
            <i data-lucide="user-check" style="width:48px;height:48px;color:var(--admin-text-tertiary);margin-bottom:12px;display:inline-block;"></i>
            <p style="color:var(--admin-text-tertiary);font-size:14px;">
                @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.</span>
                }
            </p>
        </div>
    </div>
}
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:32px;height:32px;border-radius:50%;background:linear-gradient(135deg, #FF5C00 0%, #FF8A3D 100%);display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#fff;flex-shrink:0;">
                                @GetInitials(context.Name)
                            </div>
                            <span style="font-weight:600;font-size:13px;">@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:10px;">@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)
                        {
                            <span style="font-size:11px;padding:3px 10px;border-radius:12px;background:rgba(34,197,94,0.15);color:#22C55E;">Hoat dong</span>
                        }
                        else
                        {
                            <span style="font-size:11px;padding:3px 10px;border-radius:12px;background:rgba(107,114,128,0.15);color:#6B7280;">Ngung</span>
                        }
                    </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>
}

@* ═══ 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" 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 (Enter de them)"
                          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 {
    [Parameter] public Guid ShopId { get; set; }

    private bool _loading = true;
    private bool _saving = false;
    private List<PosDataService.TherapistInfo> _therapists = new();
    private string _searchQuery = string.Empty;

    // Dialog state
    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 };

    private static readonly string[] _availableSpecialties = new[]
    {
        "Massage", "Facial", "Body Scrub", "Nail Art", "Hair Styling",
        "Waxing", "Aromatherapy", "Hot Stone", "Acupuncture", "Skin Care"
    };

    private IEnumerable<PosDataService.TherapistInfo> FilteredTherapists =>
        string.IsNullOrWhiteSpace(_searchQuery) ? _therapists
            : _therapists.Where(t => t.Name.Contains(_searchQuery, StringComparison.OrdinalIgnoreCase));

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
        {
            try { _therapists = await DataService.GetTherapistsAsync(ShopId); }
            catch { _therapists = new(); }
        }
        _loading = false;
    }

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

    private void OpenEditDialog(PosDataService.TherapistInfo t)
    {
        _editingId = t.Id;
        _formName = t.Name;
        _formPhone = t.Phone ?? string.Empty;
        _formEmail = t.Email ?? string.Empty;
        _formWorkingHours = t.WorkingHours ?? string.Empty;
        _formCustomSpecialty = string.Empty;
        _selectedSpecialties = t.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(); }

    private async Task SaveTherapistAsync()
    {
        if (_form != null) { await _form.Validate(); if (!_form.IsValid) return; }
        if (string.IsNullOrWhiteSpace(_formName) || ShopId == Guid.Empty) { Snackbar.Add("Vui long nhap ten nhan vien.", Severity.Warning); return; }

        _saving = true; StateHasChanged();
        try
        {
            var specialties = _selectedSpecialties.ToArray();
            var req = new PosDataService.CreateTherapistRequest(ShopId, _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 ok = _editingId.HasValue
                ? await DataService.UpdateTherapistAsync(_editingId.Value, req)
                : await DataService.CreateTherapistAsync(req);

            if (ok)
            {
                Snackbar.Add(_editingId.HasValue ? "Da cap nhat." : "Da them nhan vien.", Severity.Success);
                CloseDialog();
                _therapists = await DataService.GetTherapistsAsync(ShopId);
            }
            else { Snackbar.Add("Thao tac that bai.", Severity.Error); }
        }
        catch (Exception ex) { Snackbar.Add($"Loi: {ex.Message}", Severity.Error); }
        finally { _saving = false; StateHasChanged(); }
    }

    private async Task ConfirmDeactivate(PosDataService.TherapistInfo t)
    {
        var confirmed = await DialogService.ShowMessageBox("Vo hieu hoa nhan vien",
            $"Ban co chac muon vo hieu hoa '{t.Name}'?", yesText: "Vo hieu hoa", cancelText: "Huy");
        if (confirmed != true) return;
        try
        {
            if (await DataService.DeactivateTherapistAsync(t.Id))
            {
                Snackbar.Add($"Da vo hieu hoa '{t.Name}'.", Severity.Success);
                _therapists = await DataService.GetTherapistsAsync(ShopId);
            }
            else { Snackbar.Add("That bai.", 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);
        return parts.Length >= 2 ? $"{parts[0][0]}{parts[^1][0]}".ToUpper() : name[..Math.Min(2, name.Length)].ToUpper();
    }
}
