@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@inject PosDataService DataService
@inject NavigationManager Nav

@if (SubSection == "schedule")
{
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
        <div style="display:flex;gap:8px;">
            <div class="admin-stat-card" style="margin:0;"><div class="admin-stat-card__icon" style="background:rgba(139,92,246,0.1);"><i data-lucide="users" style="color:#8B5CF6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_staffSchedules.Select(s => s.StaffId).Distinct().Count()</span><span class="admin-stat-card__label">NV có lịch</span></div></div>
            <div class="admin-stat-card" style="margin:0;"><div class="admin-stat-card__icon" style="background:rgba(59,130,246,0.1);"><i data-lucide="calendar" style="color:#3B82F6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_staffSchedules.Count</span><span class="admin-stat-card__label">Ca làm việc</span></div></div>
        </div>
        <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick='() => { _showScheduleForm = !_showScheduleForm; _newSchedStaffId = Guid.Empty; _newSchedDays = new() { 1 }; _newSchedStart = "08:00"; _newSchedEnd = "17:00"; _schedFormMessage = null; }'>
            <i data-lucide="plus-circle" style="width:16px;height:16px;"></i>Thêm ca
        </button>
    </div>
    @if (_showScheduleForm)
    {
        <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">Thêm lịch làm việc</h3></div>
            <div class="admin-panel__body">
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:12px;">
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Nhân viên</label>
                        <select @bind="_newSchedStaffIdStr" 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="">-- Chọn NV --</option>
                            @foreach (var st in _staff)
                            {
                                var stName = !string.IsNullOrWhiteSpace(st.LastName) || !string.IsNullOrWhiteSpace(st.FirstName) ? $"{st.LastName} {st.FirstName}".Trim() : (st.EmployeeCode ?? st.Id.ToString()[..8]);
                                <option value="@st.Id">@stName</option>
                            }
                        </select>
                    </div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Ngày (chọn nhiều)</label>
                        <div style="display:flex;gap:4px;flex-wrap:wrap;">
                            @foreach (var (dayVal, dayName) in new[] { (1,"T2"), (2,"T3"), (3,"T4"), (4,"T5"), (5,"T6"), (6,"T7"), (0,"CN") })
                            {
                                var isSelected = _newSchedDays.Contains(dayVal);
                                var pillBg = isSelected ? "var(--admin-orange-primary)" : "var(--admin-bg-elevated)";
                                var pillColor = isSelected ? "#FFF" : "var(--admin-text-secondary)";
                                var pillBorder = isSelected ? "var(--admin-orange-primary)" : "var(--admin-border-subtle)";
                                <button type="button" @onclick="@(() => ToggleDay(dayVal))" style="padding:6px 12px;border-radius:6px;font-size:12px;font-weight:600;border:1px solid @pillBorder;background:@pillBg;color:@pillColor;cursor:pointer;">@dayName</button>
                            }
                        </div>
                    </div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Bắt đầu</label><input type="text" @bind="_newSchedStart" placeholder="08:00" 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;">Kết thúc</label><input type="text" @bind="_newSchedEnd" placeholder="17:00" 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="display:flex;gap:8px;margin-top:12px;">
                    <button class="admin-btn-primary" @onclick="AddSchedule" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>Lưu</button>
                    <button @onclick='() => _showScheduleForm = 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 (_schedFormMessage != null) { <div style="margin-top:8px;font-size:13px;color:@(_schedFormSuccess ? "#22C55E" : "#EF4444");">@_schedFormMessage</div> }
            </div>
        </div>
    }
    @if (!_staffSchedules.Any())
    {
        <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="calendar-clock" 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ó lịch làm việc</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">Thiết lập lịch ca cho nhân viên</p>
        </div>
    }
    else
    {
        <div class="admin-panel">
            <div class="admin-panel__header"><h3 class="admin-panel__title">Lịch làm việc theo tuần</h3></div>
            <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);">Vai trò</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Thứ</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Bắt đầu</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Kết thúc</th>
                    <th style="padding:12px 16px;width:48px;"></th>
                </tr></thead><tbody>
                    @foreach (var s in _staffSchedules.OrderBy(x => x.DayOfWeek).ThenBy(x => x.StartTime))
                    {
                        var schedStaff = _staff.FirstOrDefault(st => st.Id == s.StaffId);
                        var schedStaffName = schedStaff != null && (!string.IsNullOrWhiteSpace(schedStaff.LastName) || !string.IsNullOrWhiteSpace(schedStaff.FirstName)) ? $"{schedStaff.LastName} {schedStaff.FirstName}".Trim() : (s.EmployeeCode ?? s.StaffId.ToString()[..8]);
                        <tr style="border-top:1px solid var(--admin-border-subtle);">
                            <td style="padding:12px 16px;font-weight:600;">@schedStaffName</td>
                            <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-tertiary);">@(schedStaff?.Role ?? s.Role ?? "—")</td>
                            <td style="padding:12px 16px;text-align:center;font-weight:600;color:var(--admin-orange-primary);">@ShopHelpers.DayLabel(s.DayOfWeek)</td>
                            <td style="padding:12px 16px;text-align:center;">@FormatTime(s.StartTime)</td>
                            <td style="padding:12px 16px;text-align:center;">@FormatTime(s.EndTime)</td>
                            <td style="padding:12px 16px;text-align:center;"><button @onclick='() => DeleteScheduleItem(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;"><i data-lucide="trash-2" style="color:#EF4444;width:14px;height:14px;"></i></button></td>
                        </tr>
                    }
                </tbody></table>
            </div>
        </div>
    }
}
else if (SubSection == "shifts")
{
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:16px;margin-bottom:16px;">
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(59,130,246,0.1);"><i data-lucide="clock" style="color:#3B82F6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_staffSchedules.Count</span><span class="admin-stat-card__label">Ca đã phân</span></div></div>
        <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</span><span class="admin-stat-card__label">Nhân viên</span></div></div>
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(245,158,11,0.1);"><i data-lucide="calendar" style="color:#F59E0B;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_staffSchedules.Select(s => s.DayOfWeek).Distinct().Count()</span><span class="admin-stat-card__label">Ngày có ca</span></div></div>
    </div>
    @* ─── Add Schedule Form ─── *@
    <div class="admin-panel" style="margin-bottom:16px;">
        <div class="admin-panel__header" style="display:flex;justify-content:space-between;align-items:center;">
            <h3 class="admin-panel__title">Phân ca làm việc</h3>
            <button class="admin-btn-primary" style="font-size:12px;padding:6px 14px;" @onclick="@(() => { _showScheduleForm = !_showScheduleForm; _schedFormMessage = null; })"><i data-lucide="plus" style="width:14px;height:14px;margin-right:4px;"></i>Thêm ca</button>
        </div>
        @if (_showScheduleForm)
        {
            <div style="padding:16px;border-top:1px solid var(--admin-border-subtle);">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;align-items:end;">
                    <div style="grid-column:span 1;"><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Nhân viên</label>
                        <select @bind="_newSchedStaffIdStr" 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);font-size:13px;">
                            <option value="">-- Chọn NV --</option>
                            @foreach (var s in _staff) {
                                var sName = !string.IsNullOrWhiteSpace(s.LastName) || !string.IsNullOrWhiteSpace(s.FirstName) ? $"{s.LastName} {s.FirstName}".Trim() : (s.EmployeeCode ?? s.Id.ToString()[..8]);
                                <option value="@s.Id">@sName</option>
                            }
                        </select>
                    </div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Ngày (chọn nhiều)</label>
                        <div style="display:flex;gap:4px;flex-wrap:wrap;">
                            @foreach (var (dayVal, dayName) in new[] { (1,"T2"), (2,"T3"), (3,"T4"), (4,"T5"), (5,"T6"), (6,"T7"), (0,"CN") })
                            {
                                var isSelected = _newSchedDays.Contains(dayVal);
                                var pillBg = isSelected ? "var(--admin-orange-primary)" : "var(--admin-bg-elevated)";
                                var pillColor = isSelected ? "#FFF" : "var(--admin-text-secondary)";
                                var pillBorder = isSelected ? "var(--admin-orange-primary)" : "var(--admin-border-subtle)";
                                <button type="button" @onclick="@(() => ToggleDay(dayVal))" style="padding:6px 12px;border-radius:6px;font-size:12px;font-weight:600;border:1px solid @pillBorder;background:@pillBg;color:@pillColor;cursor:pointer;">@dayName</button>
                            }
                        </div>
                    </div>
                    <div style="grid-column:span 2;"><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Ca mẫu</label>
                        <div style="display:flex;gap:6px;">
                            <button type="button" @onclick='@(() => { _newSchedStart = "07:00"; _newSchedEnd = "12:00"; })' style="padding:4px 10px;border-radius:6px;font-size:11px;border:1px solid rgba(59,130,246,0.3);background:rgba(59,130,246,0.1);color:#3B82F6;cursor:pointer;font-weight:600;">Sáng 7-12h</button>
                            <button type="button" @onclick='@(() => { _newSchedStart = "12:00"; _newSchedEnd = "17:00"; })' style="padding:4px 10px;border-radius:6px;font-size:11px;border:1px solid rgba(168,85,247,0.3);background:rgba(168,85,247,0.1);color:#A855F7;cursor:pointer;font-weight:600;">Chiều 12-17h</button>
                            <button type="button" @onclick='@(() => { _newSchedStart = "17:00"; _newSchedEnd = "22:00"; })' style="padding:4px 10px;border-radius:6px;font-size:11px;border:1px solid rgba(245,158,11,0.3);background:rgba(245,158,11,0.1);color:#F59E0B;cursor:pointer;font-weight:600;">Tối 17-22h</button>
                            <button type="button" @onclick='@(() => { _newSchedStart = "08:00"; _newSchedEnd = "17:00"; })' style="padding:4px 10px;border-radius:6px;font-size:11px;border:1px solid rgba(34,197,94,0.3);background:rgba(34,197,94,0.1);color:#22C55E;cursor:pointer;font-weight:600;">Full 8-17h</button>
                        </div>
                    </div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Giờ bắt đầu</label><input type="text" @bind="_newSchedStart" placeholder="08:00" 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);font-size:13px;" /></div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Giờ kết thúc</label><input type="text" @bind="_newSchedEnd" placeholder="17:00" 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);font-size:13px;" /></div>
                </div>
                <div style="display:flex;gap:8px;margin-top:12px;">
                    <button class="admin-btn-primary" style="font-size:12px;padding:6px 16px;" @onclick="AddSchedule">Lưu</button>
                    <button style="padding:6px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);font-size:12px;cursor:pointer;" @onclick="@(() => _showScheduleForm = false)">Hủy</button>
                </div>
                @if (_schedFormMessage != null) { <div style="margin-top:8px;font-size:13px;color:@(_schedFormSuccess ? "#22C55E" : "#EF4444");">@_schedFormMessage</div> }
            </div>
        }
    </div>
    @* ─── Weekly Grid ─── *@
    <div class="admin-panel">
        <div class="admin-panel__header"><h3 class="admin-panel__title">Lịch ca — Tuần</h3></div>
        <div class="admin-panel__body" style="padding:0;overflow-x:auto;">
            @if (!_staff.Any())
            {
                <div style="text-align:center;padding:40px 20px;color:var(--admin-text-tertiary);font-size:14px;">Chưa có nhân viên. Thêm nhân viên trong mục <a href="/admin/shop/@ShopId/staff" style="color:var(--admin-orange-primary);">Nhân sự</a>.</div>
            }
            else
            {
                <table class="admin-table" style="width:100%;min-width:700px;"><thead><tr>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);white-space:nowrap;">Nhân viên</th>
                    @foreach (var d in new[] { "T2", "T3", "T4", "T5", "T6", "T7", "CN" })
                    {
                        <th style="padding:12px 8px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);min-width:80px;">@d</th>
                    }
                </tr></thead><tbody>
                    @foreach (var emp in _staff)
                    {
                        <tr style="border-top:1px solid var(--admin-border-subtle);">
                            @{ var empName = !string.IsNullOrWhiteSpace(emp.LastName) || !string.IsNullOrWhiteSpace(emp.FirstName) ? $"{emp.LastName} {emp.FirstName}".Trim() : (emp.EmployeeCode ?? emp.Id.ToString()[..8]); }
                            <td style="padding:12px 16px;font-weight:600;white-space:nowrap;">@empName</td>
                            @foreach (var dow in new[] { 1, 2, 3, 4, 5, 6, 0 })
                            {
                                var scheds = _staffSchedules.Where(s => s.StaffId == emp.Id && s.DayOfWeek == dow)
                                                            .OrderBy(s => s.StartTime).ToList();
                                <td style="padding:4px 2px;text-align:center;vertical-align:top;">
                                @if (scheds.Any())
                                {
                                    <div style="display:flex;flex-direction:column;gap:2px;align-items:center;">
                                    @foreach (var sched in scheds)
                                    {
                                        var isMorning = sched.StartTime?.CompareTo("12:00") < 0;
                                        var isEvening = sched.StartTime?.CompareTo("18:00") >= 0;
                                        var bg = isEvening ? "rgba(245,158,11,0.12)" : isMorning ? "rgba(59,130,246,0.12)" : "rgba(168,85,247,0.12)";
                                        var fg = isEvening ? "#F59E0B" : isMorning ? "#3B82F6" : "#A855F7";
                                        var label = $"{sched.StartTime?[..5]}-{sched.EndTime?[..5]}";
                                        <div style="display:inline-flex;align-items:center;gap:1px;">
                                            <span title="@(sched.StartTime) - @(sched.EndTime)" style="display:inline-block;padding:2px 4px;border-radius:4px;font-size:10px;font-weight:700;background:@bg;color:@fg;white-space:nowrap;">@label</span>
                                            <button @onclick="@(() => DeleteScheduleItem(sched.Id))" style="background:none;border:none;cursor:pointer;padding:0;line-height:1;" title="Xóa"><i data-lucide="x" style="width:8px;height:8px;color:#EF4444;"></i></button>
                                        </div>
                                    }
                                    </div>
                                }
                                else
                                {
                                    <span style="display:inline-block;width:36px;height:28px;line-height:28px;border-radius:6px;font-size:12px;font-weight:700;color:var(--admin-text-tertiary);">—</span>
                                }
                                </td>
                            }
                        </tr>
                    }
                </tbody></table>
            }
        </div>
    </div>
    <div style="display:flex;gap:16px;margin-top:12px;">
        <div style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--admin-text-tertiary);"><span style="display:inline-block;width:12px;height:12px;border-radius:3px;background:rgba(59,130,246,0.25);"></span> Sáng (&lt;12:00)</div>
        <div style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--admin-text-tertiary);"><span style="display:inline-block;width:12px;height:12px;border-radius:3px;background:rgba(168,85,247,0.25);"></span> Chiều (≥12:00)</div>
        <div style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--admin-text-tertiary);"><span style="display:inline-block;width:12px;height:12px;border-radius:3px;background:rgba(245,158,11,0.25);"></span> Tối (≥18:00)</div>
        <div style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--admin-text-tertiary);"><span style="display:inline-block;width:12px;height:12px;border-radius:3px;background:transparent;border:1px solid var(--admin-border-subtle);"></span> — = Nghỉ</div>
    </div>
}

@code {
    [Parameter] public Guid ShopId { get; set; }
    [Parameter] public string SubSection { get; set; } = "schedule";

    private List<PosDataService.StaffInfo> _staff = new();
    private List<PosDataService.ScheduleInfo> _staffSchedules = new();
    private bool _showScheduleForm;
    private Guid _newSchedStaffId;
    private string _newSchedStaffIdStr = "";
    private HashSet<int> _newSchedDays = new() { 1 };
    private string _newSchedStart = "08:00";
    private string _newSchedEnd = "17:00";
    private string? _schedFormMessage;
    private bool _schedFormSuccess;

    protected override async Task OnInitializedAsync()
    {
        _staffSchedules = await DataService.GetStaffSchedulesAsync(ShopId != Guid.Empty ? ShopId : null);
        _staff = await DataService.GetStaffForShopAsync(ShopId);
    }

    private void ToggleDay(int day)
    {
        if (_newSchedDays.Contains(day))
            _newSchedDays.Remove(day);
        else
            _newSchedDays.Add(day);
    }

    private async Task AddSchedule()
    {
        _schedFormMessage = null;
        if (!Guid.TryParse(_newSchedStaffIdStr, out var staffId) || ShopId == Guid.Empty)
        {
            _schedFormMessage = "Vui lòng chọn nhân viên."; _schedFormSuccess = false; return;
        }
        if (!_newSchedDays.Any())
        {
            _schedFormMessage = "Vui lòng chọn ít nhất 1 ngày."; _schedFormSuccess = false; return;
        }
        try
        {
            _newSchedStaffId = staffId;
            foreach (var day in _newSchedDays.OrderBy(d => d))
            {
                await DataService.CreateScheduleAsync(new PosDataService.CreateScheduleRequest(ShopId, _newSchedStaffId, day, _newSchedStart, _newSchedEnd));
            }
            _schedFormMessage = $"Đã thêm {_newSchedDays.Count} ca làm việc thành công!"; _schedFormSuccess = true;
            _showScheduleForm = false;
            _staffSchedules = await DataService.GetStaffSchedulesAsync(ShopId != Guid.Empty ? ShopId : null);
        }
        catch (Exception ex) { _schedFormMessage = $"Lỗi: {ex.Message}"; _schedFormSuccess = false; }
    }

    private async Task DeleteScheduleItem(Guid id)
    {
        try
        {
            await DataService.DeleteScheduleAsync(id);
            _staffSchedules = await DataService.GetStaffSchedulesAsync(ShopId != Guid.Empty ? ShopId : null);
        }
        catch (Exception ex) { Console.Error.WriteLine($"Không thể xóa lịch làm việc: {ex.Message}"); }
    }

    /// <summary>
    /// EN: Format time string — remove seconds if present (08:00:00 → 08:00).
    /// VI: Định dạng giờ — bỏ giây nếu có (08:00:00 → 08:00).
    /// </summary>
    private static string FormatTime(string? time)
    {
        if (string.IsNullOrEmpty(time)) return "—";
        var parts = time.Split(':');
        return parts.Length >= 2 ? $"{parts[0]}:{parts[1]}" : time;
    }
}
