@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@using Microsoft.AspNetCore.Components.Forms
@inject PosDataService DataService

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
    <h3 style="margin:0;font-size:16px;font-weight:700;">@(_staff.Count) nhân viên</h3>
    <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick="@(() => { _editingStaffId = null; _newStaffCode = ""; _newStaffPhone = ""; _newStaffEmail = ""; _newStaffRole = "Cashier"; _staffFormMessage = null; _createStaffAccount = false; _newStaffFirstName = ""; _newStaffLastName = ""; _newStaffPassword = ""; _newStaffAddress = ""; _staffDocFrontFile = null; _staffDocBackFile = null; _staffDocFrontPreview = null; _staffDocBackPreview = null; _showStaffForm = !_showStaffForm; })">
        <i data-lucide="user-plus" style="width:16px;height:16px;"></i>
        Thêm nhân viên
    </button>
</div>
@if (_showStaffForm)
{
    <div class="admin-panel" style="margin-bottom:16px;border:1px solid rgba(139,92,246,0.3);">
        <div class="admin-panel__header"><h3 class="admin-panel__title">@(_editingStaffId.HasValue ? "Chỉnh sửa nhân viên" : "Thêm nhân viên mới")</h3></div>
        <div class="admin-panel__body">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Họ</label><input type="text" @bind="_newStaffLastName" placeholder="Nguyễn" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Tên</label><input type="text" @bind="_newStaffFirstName" placeholder="Văn A" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Mã NV *</label><input type="text" @bind="_newStaffCode" placeholder="VD: NV001" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Vai trò</label>
                    <select @bind="_newStaffRole" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                        <option value="Cashier">Thu ngân</option>
                        <option value="Waiter">Phục vụ</option>
                        <option value="Chef">Bếp</option>
                        <option value="Manager">Quản lý</option>
                        <option value="Therapist">Therapist</option>
                    </select>
                </div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">SĐT</label><input type="text" @bind="_newStaffPhone" placeholder="0912345678" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Email *</label><input type="email" @bind="_newStaffEmail" placeholder="nv@goodgo.vn" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                <div style="grid-column:span 2;"><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Địa chỉ</label><input type="text" @bind="_newStaffAddress" placeholder="Số nhà, đường, phường..." style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
            </div>
            <div style="margin-top:12px;">
                <label style="font-size:12px;font-weight:600;display:block;margin-bottom:8px;">CCCD / Giấy tờ tùy thân</label>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                    <div style="border:2px dashed var(--admin-border-subtle);border-radius:8px;padding:12px;text-align:center;">
                        <label style="font-size:11px;color:var(--admin-text-tertiary);display:block;margin-bottom:6px;">Mặt trước</label>
                        @if (_staffDocFrontPreview != null)
                        {
                            <img src="@_staffDocFrontPreview" alt="CCCD trước" style="max-width:100%;max-height:100px;border-radius:6px;margin-bottom:6px;" />
                        }
                        <InputFile OnChange="OnStaffDocFrontSelected" accept="image/*" style="font-size:12px;width:100%;" />
                    </div>
                    <div style="border:2px dashed var(--admin-border-subtle);border-radius:8px;padding:12px;text-align:center;">
                        <label style="font-size:11px;color:var(--admin-text-tertiary);display:block;margin-bottom:6px;">Mặt sau</label>
                        @if (_staffDocBackPreview != null)
                        {
                            <img src="@_staffDocBackPreview" alt="CCCD sau" style="max-width:100%;max-height:100px;border-radius:6px;margin-bottom:6px;" />
                        }
                        <InputFile OnChange="OnStaffDocBackSelected" accept="image/*" style="font-size:12px;width:100%;" />
                    </div>
                </div>
            </div>
            @if (!_editingStaffId.HasValue)
            {
                <div style="margin-top:12px;padding:12px;border-radius:8px;background:rgba(139,92,246,0.05);border:1px solid rgba(139,92,246,0.2);">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;font-weight:600;">
                        <input type="checkbox" @bind="_createStaffAccount" /> Tạo tài khoản đăng nhập (IAM)
                    </label>
                    @if (_createStaffAccount)
                    {
                        <div style="margin-top:10px;">
                            <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Mật khẩu *</label><input type="password" @bind="_newStaffPassword" placeholder="Min 8 ký tự" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                        </div>
                    }
                </div>
            }
            <div style="display:flex;gap:8px;margin-top:16px;">
                <button class="admin-btn-primary" @onclick="@(_editingStaffId.HasValue ? SaveStaffEdit : AddStaff)" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>@(_editingStaffId.HasValue ? "Cập nhật" : "Lưu")</button>
                <button @onclick="@(() => _showStaffForm = false)" style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;"><i data-lucide="x" style="width:14px;height:14px;"></i>Hủy</button>
            </div>
            @if (!string.IsNullOrEmpty(_staffFormMessage))
            {
                <div style="margin-top:8px;font-size:13px;color:@(_staffFormSuccess ? "#22C55E" : "#EF4444");">@_staffFormMessage</div>
            }
        </div>
    </div>
}
@if (!_staff.Any() && !_showStaffForm)
{
    <div style="text-align:center;padding:60px 20px;">
        <div style="width:80px;height:80px;border-radius:24px;background:rgba(139,92,246,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
            <i data-lucide="users" style="width:36px;height:36px;color:#8B5CF6;"></i>
        </div>
        <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">Chưa có nhân viên</h2>
        <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">Thêm nhân viên để quản lý cửa hàng</p>
        <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick="@(() => { _editingStaffId = null; _newStaffCode = ""; _newStaffPhone = ""; _newStaffEmail = ""; _newStaffRole = "Cashier"; _staffFormMessage = null; _createStaffAccount = false; _showStaffForm = true; })">
            <i data-lucide="user-plus" style="width:16px;height:16px;"></i> Thêm nhân viên
        </button>
    </div>
}
else if (_staff.Any())
{
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;">
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(34,197,94,0.1);"><i data-lucide="user-check" style="color:#22C55E;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_staff.Count(s => s.Status == "Active")</span><span class="admin-stat-card__label">Đang hoạt động</span></div></div>
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(59,130,246,0.1);"><i data-lucide="users" style="color:#3B82F6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_staff.Count</span><span class="admin-stat-card__label">Tổng nhân viên</span></div></div>
    </div>
    <div class="admin-panel" style="margin-top:16px;">
        <div class="admin-panel__body" style="padding:0;">
            <table class="admin-table" style="width:100%;"><thead><tr>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Nhân viên</th>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Mã NV</th>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Vai trò</th>
                <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Trạng thái</th>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">SĐT</th>
                <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Hành động</th>
            </tr></thead><tbody>
                @foreach (var s in _staff)
                {
                    var staffDisplayName = !string.IsNullOrWhiteSpace(s.LastName) || !string.IsNullOrWhiteSpace(s.FirstName) ? $"{s.LastName} {s.FirstName}".Trim() : null;
                    <tr style="border-top:1px solid var(--admin-border-subtle);">
                        <td style="padding:12px 16px;font-weight:600;">@(staffDisplayName ?? s.EmployeeCode ?? s.Id.ToString()[..6])</td>
                        <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-secondary);">@(s.EmployeeCode ?? "—")</td>
                        <td style="padding:12px 16px;">@(s.Role ?? "—")</td>
                        <td style="padding:12px 16px;text-align:center;"><span class="admin-status-badge @(s.Status == "Active" ? "admin-status-badge--online" : "admin-status-badge--offline")" style="font-size:11px;padding:2px 10px;"><span class="admin-status-badge__dot" style="width:5px;height:5px;"></span>@(s.Status ?? "—")</span></td>
                        <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-tertiary);">@(s.Phone ?? s.Email ?? "—")</td>
                        <td style="padding:12px 16px;text-align:center;">
                            <div style="display:flex;gap:4px;justify-content:center;">
                                <button @onclick="@(() => EditStaff(s))" style="background:rgba(59,130,246,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Sửa"><i data-lucide="pencil" style="color:#3B82F6;width:14px;height:14px;"></i></button>
                                <button @onclick="@(() => DeleteStaffMember(s.Id))" style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Xóa"><i data-lucide="trash-2" style="color:#EF4444;width:14px;height:14px;"></i></button>
                            </div>
                        </td>
                    </tr>
                }
            </tbody></table>
        </div>
    </div>
}

@code {
    [Parameter] public Guid ShopId { get; set; }

    // Staff data
    private List<PosDataService.StaffInfo> _staff = new();
    // Staff form state
    private bool _showStaffForm;
    private Guid? _editingStaffId;
    private string _newStaffCode = "";
    private string _newStaffRole = "Cashier";
    private string _newStaffPhone = "";
    private string _newStaffEmail = "";
    private string? _staffFormMessage;
    private bool _staffFormSuccess;
    private bool _createStaffAccount;
    private string _newStaffFirstName = "";
    private string _newStaffLastName = "";
    private string _newStaffPassword = "";
    // Staff extended fields state
    private string _newStaffAddress = "";
    // Image upload state for staff docs
    private IBrowserFile? _staffDocFrontFile;
    private string? _staffDocFrontPreview;
    private IBrowserFile? _staffDocBackFile;
    private string? _staffDocBackPreview;
    // Merchant ID loaded from shop data
    private Guid? _merchantId;

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
        {
            var shop = await DataService.GetShopByIdAsync(ShopId);
            if (shop != null)
                _merchantId = shop.MerchantId;
            _staff = await DataService.GetStaffForShopAsync(ShopId);
        }
    }

    private async Task AddStaff()
    {
        _staffFormMessage = null;
        if (!_merchantId.HasValue)
        {
            _staffFormMessage = "Không tìm thấy thông tin merchant. Vui lòng tải lại trang."; _staffFormSuccess = false; return;
        }
        if (string.IsNullOrWhiteSpace(_newStaffCode))
        {
            _staffFormMessage = "Vui lòng nhập mã nhân viên."; _staffFormSuccess = false; return;
        }
        try
        {
            var docFrontUrl = await UploadFileIfNeeded(_staffDocFrontFile);
            var docBackUrl = await UploadFileIfNeeded(_staffDocBackFile);
            if (_createStaffAccount)
            {
                if (string.IsNullOrWhiteSpace(_newStaffEmail) || string.IsNullOrWhiteSpace(_newStaffPassword))
                {
                    _staffFormMessage = "Vui lòng nhập đầy đủ email và mật khẩu."; _staffFormSuccess = false; return;
                }
                var (ok, err) = await DataService.InviteStaffWithAccountAsync(new PosDataService.InviteStaffWithAccountRequest(
                    _newStaffEmail, _newStaffPassword, _newStaffFirstName, _newStaffLastName, _newStaffRole, ShopId));
                if (!ok) { _staffFormMessage = err ?? "Lỗi tạo tài khoản IAM. Kiểm tra email/mật khẩu."; _staffFormSuccess = false; return; }
                _staffFormMessage = $"Đã tạo tài khoản + mời NV '{_newStaffEmail}' thành công!"; _staffFormSuccess = true;
            }
            else
            {
                await DataService.CreateStaffAsync(new PosDataService.CreateStaffRequest(
                    _merchantId.Value, _newStaffCode, _newStaffPhone, _newStaffEmail, _newStaffRole,
                    _newStaffFirstName, _newStaffLastName, _newStaffAddress, null, docFrontUrl, docBackUrl));
                _staffFormMessage = $"Đã thêm NV '{_newStaffCode}' thành công!"; _staffFormSuccess = true;
            }
            _newStaffCode = ""; _newStaffPhone = ""; _newStaffEmail = ""; _newStaffFirstName = ""; _newStaffLastName = ""; _newStaffPassword = ""; _newStaffAddress = ""; _createStaffAccount = false;
            _staffDocFrontFile = null; _staffDocBackFile = null; _staffDocFrontPreview = null; _staffDocBackPreview = null;
            _staff = await DataService.GetStaffForShopAsync(ShopId);
        }
        catch (Exception ex) { _staffFormMessage = $"Lỗi: {ex.Message}"; _staffFormSuccess = false; }
    }

    private void EditStaff(PosDataService.StaffInfo s)
    {
        _editingStaffId = s.Id;
        _newStaffCode = s.EmployeeCode ?? "";
        _newStaffRole = s.Role ?? "Cashier";
        _newStaffPhone = s.Phone ?? "";
        _newStaffEmail = s.Email ?? "";
        _newStaffFirstName = s.FirstName ?? "";
        _newStaffLastName = s.LastName ?? "";
        _newStaffAddress = s.Address ?? "";
        _staffDocFrontFile = null; _staffDocBackFile = null;
        _staffDocFrontPreview = s.DocumentFrontUrl;
        _staffDocBackPreview = s.DocumentBackUrl;
        _staffFormMessage = null;
        _showStaffForm = true;
    }

    private async Task SaveStaffEdit()
    {
        _staffFormMessage = null;
        if (string.IsNullOrWhiteSpace(_newStaffCode) || !_merchantId.HasValue || !_editingStaffId.HasValue)
        {
            _staffFormMessage = "Vui lòng nhập Mã NV."; _staffFormSuccess = false; return;
        }
        try
        {
            var docFrontUrl = await UploadFileIfNeeded(_staffDocFrontFile) ?? (_staffDocFrontPreview?.StartsWith("data:") == true ? null : _staffDocFrontPreview);
            var docBackUrl = await UploadFileIfNeeded(_staffDocBackFile) ?? (_staffDocBackPreview?.StartsWith("data:") == true ? null : _staffDocBackPreview);
            await DataService.UpdateStaffAsync(_editingStaffId.Value, new PosDataService.CreateStaffRequest(
                _merchantId.Value, _newStaffCode, _newStaffPhone, _newStaffEmail, _newStaffRole,
                _newStaffFirstName, _newStaffLastName, _newStaffAddress, null, docFrontUrl, docBackUrl));
            _staffFormMessage = $"Đã cập nhật NV '{_newStaffCode}' thành công!"; _staffFormSuccess = true;
            _editingStaffId = null;
            _staffDocFrontFile = null; _staffDocBackFile = null; _staffDocFrontPreview = null; _staffDocBackPreview = null;
            _staff = await DataService.GetStaffForShopAsync(ShopId);
        }
        catch (Exception ex) { _staffFormMessage = $"Lỗi: {ex.Message}"; _staffFormSuccess = false; }
    }

    private async Task DeleteStaffMember(Guid staffId)
    {
        try
        {
            await DataService.DeleteStaffAsync(staffId);
            _staff = await DataService.GetStaffForShopAsync(ShopId);
        }
        catch (Exception ex) { Console.Error.WriteLine($"Không thể xóa nhân viên: {ex.Message}"); }
    }

    private async Task OnStaffDocFrontSelected(InputFileChangeEventArgs e)
    {
        _staffDocFrontFile = e.File;
        var format = "image/png";
        var resized = await e.File.RequestImageFileAsync(format, 300, 200);
        var buffer = new byte[resized.Size];
        await resized.OpenReadStream().ReadAsync(buffer);
        _staffDocFrontPreview = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
        StateHasChanged();
    }

    private async Task OnStaffDocBackSelected(InputFileChangeEventArgs e)
    {
        _staffDocBackFile = e.File;
        var format = "image/png";
        var resized = await e.File.RequestImageFileAsync(format, 300, 200);
        var buffer = new byte[resized.Size];
        await resized.OpenReadStream().ReadAsync(buffer);
        _staffDocBackPreview = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
        StateHasChanged();
    }

    private async Task<string?> UploadFileIfNeeded(IBrowserFile? file)
    {
        if (file == null) return null;
        using var stream = file.OpenReadStream(maxAllowedSize: 10_485_760);
        return await DataService.UploadImageAsync(stream, file.Name, file.ContentType);
    }
}
