@*
    EN: Therapist Schedule — Calendar day view with horizontal timeline, staff rows, appointment blocks, current time.
    VI: Lịch kỹ thuật viên — Xem theo ngày với timeline ngang, hàng nhân viên, khối lịch hẹn, thời gian hiện tại.
*@
@page "/pos/{ShopId:guid}/spa/therapist-schedule"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ HEADER / TIÊU ĐỀ ═══ *@
    <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);flex-shrink:0;">
        <div style="display:flex;align-items:center;gap:12px;">
            <button style="background:var(--pos-bg-interactive);border:none;color:var(--pos-text-primary);
                           padding:8px 12px;border-radius:8px;cursor:pointer;font-size:13px;"
                    @onclick="@(() => NavigateTo("spa"))">
                <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
            </button>
            <span style="font-size:16px;font-weight:700;">Lịch kỹ thuật viên</span>
            <span style="font-size:13px;color:var(--pos-text-tertiary);">Hôm nay, @DateTime.Now.ToString("dd/MM/yyyy")</span>
        </div>

        @* EN: Legend / VI: Chú thích *@
        <div style="display:flex;gap:12px;font-size:11px;">
            <span style="display:flex;align-items:center;gap:4px;">
                <span style="width:10px;height:10px;border-radius:3px;background:rgba(255,92,0,.3);"></span> Massage
            </span>
            <span style="display:flex;align-items:center;gap:4px;">
                <span style="width:10px;height:10px;border-radius:3px;background:rgba(139,92,246,.3);"></span> Facial
            </span>
            <span style="display:flex;align-items:center;gap:4px;">
                <span style="width:10px;height:10px;border-radius:3px;background:rgba(34,197,94,.3);"></span> Body
            </span>
            <span style="display:flex;align-items:center;gap:4px;">
                <span style="width:10px;height:10px;border-radius:3px;background:rgba(59,130,246,.3);"></span> Nail/Hair
            </span>
        </div>
    </div>

    @* ═══ SCHEDULE GRID / LƯỚI LỊCH ═══ *@
    @if (_isLoading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Đang tải lịch...
        </div>
    }
    else if (_loadError)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu lịch
        </div>
    }
    else
    {
    <div style="flex:1;overflow:auto;position:relative;">
        @* EN: Time header row / VI: Hàng tiêu đề giờ *@
        <div style="display:flex;position:sticky;top:0;z-index:10;background:var(--pos-bg-elevated);border-bottom:1px solid var(--pos-border-subtle);">
            <div style="width:140px;min-width:140px;padding:10px 12px;font-size:12px;font-weight:600;color:var(--pos-text-tertiary);
                        border-right:1px solid var(--pos-border-subtle);">
                Nhân viên
            </div>
            <div style="display:flex;flex:1;">
                @foreach (var hour in _hours)
                {
                    <div style="min-width:100px;padding:10px 8px;text-align:center;font-size:12px;font-weight:500;
                                color:var(--pos-text-tertiary);border-right:1px solid var(--pos-border-subtle);">
                        @hour:00
                    </div>
                }
            </div>
        </div>

        @* EN: Staff rows / VI: Hàng nhân viên *@
        @foreach (var staff in _scheduleData)
        {
            <div style="display:flex;border-bottom:1px solid var(--pos-border-subtle);min-height:64px;">
                @* EN: Staff name column / VI: Cột tên nhân viên *@
                <div style="width:140px;min-width:140px;padding:12px;display:flex;align-items:center;gap:8px;
                            border-right:1px solid var(--pos-border-subtle);flex-shrink:0;">
                    <div style="width:32px;height:32px;border-radius:50%;background:var(--pos-bg-interactive);
                                display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;flex-shrink:0;">
                        @staff.Name[..1]
                    </div>
                    <div>
                        <div style="font-size:12px;font-weight:600;">@staff.Name</div>
                        <div style="font-size:10px;color:var(--pos-text-tertiary);">@staff.Role</div>
                    </div>
                </div>

                @* EN: Timeline with blocks / VI: Timeline với khối lịch *@
                <div style="flex:1;position:relative;display:flex;">
                    @foreach (var hour in _hours)
                    {
                        <div style="min-width:100px;border-right:1px solid var(--pos-border-subtle);"></div>
                    }

                    @* EN: Appointment blocks / VI: Khối lịch hẹn *@
                    @foreach (var appt in staff.Appointments)
                    {
                        var leftPos = (appt.StartHour - 9) * 100 + (appt.StartMin / 30.0 * 50);
                        var widthVal = appt.DurationMin / 30.0 * 50;
                        <div style="position:absolute;left:@(leftPos)px;top:8px;bottom:8px;width:@(widthVal)px;
                                    background:@GetServiceBg(appt.Type);border-left:3px solid @GetServiceColor(appt.Type);
                                    border-radius:6px;padding:4px 8px;overflow:hidden;cursor:pointer;"
                             @onclick="@(() => NavigateTo("spa/treatment-timer"))">
                            <div style="font-size:11px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                                @appt.CustomerName
                            </div>
                            <div style="font-size:10px;color:var(--pos-text-tertiary);white-space:nowrap;">
                                @appt.Service
                            </div>
                        </div>
                    }
                </div>
            </div>
        }

        @* EN: Current time indicator / VI: Chỉ báo thời gian hiện tại *@
        <div style="position:absolute;top:0;bottom:0;left:@(140 + (DateTime.Now.Hour - 9) * 100 + DateTime.Now.Minute / 30.0 * 50)px;
                    width:2px;background:var(--pos-danger);z-index:5;">
            <div style="position:absolute;top:-4px;left:-4px;width:10px;height:10px;border-radius:50%;background:var(--pos-danger);"></div>
        </div>
    </div>

    }

    @* ═══ SUMMARY / TÓM TẮT ═══ *@
    <div style="padding:10px 16px;border-top:1px solid var(--pos-border-subtle);display:flex;gap:20px;font-size:12px;color:var(--pos-text-secondary);flex-shrink:0;">
        <span>Tổng: <b>@_scheduleData.Sum(s => s.Appointments.Count)</b> lịch hẹn</span>
        <span style="color:var(--pos-orange-primary);">Đang thực hiện: <b>@_inProgressCount</b></span>
        <span style="color:var(--pos-success);">Hoàn thành: <b>@_completedCount</b></span>
        <span style="color:var(--pos-text-tertiary);">Sắp tới: <b>@_upcomingCount</b></span>
    </div>
</div>

@code {
    // EN: Loading state / VI: Trạng thái tải
    private bool _isLoading = true;
    private bool _loadError;

    // EN: Hours range / VI: Phạm vi giờ
    private readonly int[] _hours = { 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
    private List<StaffSchedule> _scheduleData = new();

    // EN: Summary counters / VI: Bộ đếm tóm tắt
    private int _inProgressCount;
    private int _completedCount;
    private int _upcomingCount;

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

        try
        {
            // EN: Load staff and appointments in parallel / VI: Tải nhân viên và lịch hẹn song song
            var staffTask = DataService.GetStaffForShopAsync(ShopId);
            var appointmentsTask = DataService.GetAppointmentsAsync(ShopId);

            var staffData = await staffTask;
            var appointments = await appointmentsTask;

            // EN: Filter today's appointments / VI: Lọc lịch hẹn hôm nay
            var todayAppointments = appointments
                .Where(a => a.StartTime.Date == DateTime.Today)
                .ToList();

            // EN: Count by status / VI: Đếm theo trạng thái
            var now = DateTime.Now;
            _completedCount = todayAppointments.Count(a => a.Status?.ToLower() == "completed");
            _inProgressCount = todayAppointments.Count(a => a.StartTime <= now && a.EndTime >= now && a.Status?.ToLower() != "completed" && a.Status?.ToLower() != "cancelled");
            _upcomingCount = todayAppointments.Count(a => a.StartTime > now && a.Status?.ToLower() != "cancelled");

            // EN: Group appointments by staff / VI: Nhóm lịch hẹn theo nhân viên
            var staffMap = staffData.ToDictionary(s => s.Id, s =>
            {
                var name = $"{s.FirstName ?? ""} {s.LastName ?? ""}".Trim();
                if (string.IsNullOrEmpty(name)) name = s.EmployeeCode ?? s.Id.ToString()[..8];
                return (Name: name, Role: s.Role ?? "Nhân viên");
            });

            // EN: Build schedule data — group by staff / VI: Xây dựng dữ liệu lịch — nhóm theo nhân viên
            var grouped = todayAppointments
                .Where(a => a.StaffId.HasValue)
                .GroupBy(a => a.StaffId!.Value)
                .ToList();

            _scheduleData = new();

            foreach (var group in grouped)
            {
                var staffName = staffMap.TryGetValue(group.Key, out var info) ? info.Name : group.Key.ToString()[..8];
                var staffRole = staffMap.TryGetValue(group.Key, out var info2) ? info2.Role : "Nhân viên";

                var blocks = group.Select(a => new AppointmentBlock(
                    a.ResourceName ?? "Khách",
                    a.ResourceName ?? "Dịch vụ",
                    GuessServiceType(a.ResourceName),
                    a.StartTime.Hour,
                    a.StartTime.Minute,
                    (int)(a.EndTime - a.StartTime).TotalMinutes
                )).ToList();

                _scheduleData.Add(new StaffSchedule(staffName, staffRole, blocks));
            }

            // EN: Add staff without appointments / VI: Thêm nhân viên chưa có lịch hẹn
            var assignedStaffIds = grouped.Select(g => g.Key).ToHashSet();
            foreach (var s in staffData.Where(s => !assignedStaffIds.Contains(s.Id)))
            {
                var name = $"{s.FirstName ?? ""} {s.LastName ?? ""}".Trim();
                if (string.IsNullOrEmpty(name)) name = s.EmployeeCode ?? s.Id.ToString()[..8];
                _scheduleData.Add(new StaffSchedule(name, s.Role ?? "Nhân viên", new()));
            }
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    // EN: Guess service type from name for color coding / VI: Đoán loại dịch vụ từ tên để tô màu
    private static string GuessServiceType(string? name)
    {
        if (name is null) return "Other";
        var lower = name.ToLower();
        if (lower.Contains("massage")) return "Massage";
        if (lower.Contains("facial") || lower.Contains("mặt")) return "Facial";
        if (lower.Contains("body") || lower.Contains("tắm") || lower.Contains("tẩy")) return "Body";
        if (lower.Contains("nail") || lower.Contains("hair") || lower.Contains("tóc") || lower.Contains("móng")) return "Nail";
        return "Other";
    }

    private static string GetServiceBg(string type) => type switch
    {
        "Massage" => "rgba(255,92,0,.15)", "Facial" => "rgba(139,92,246,.15)",
        "Body" => "rgba(34,197,94,.15)", _ => "rgba(59,130,246,.15)"
    };

    private static string GetServiceColor(string type) => type switch
    {
        "Massage" => "#FF5C00", "Facial" => "#8B5CF6",
        "Body" => "#22C55E", _ => "#3B82F6"
    };

    private record AppointmentBlock(string CustomerName, string Service, string Type, int StartHour, int StartMin, int DurationMin);
    private record StaffSchedule(string Name, string Role, List<AppointmentBlock> Appointments);
}
