@*
    EN: Doctor Schedule — Calendar day view with horizontal timeline, doctor/specialist rows, appointment blocks, current time.
    VI: Lich Bac Si — Xem theo ngay voi timeline ngang, hang bac si/chuyen gia, khoi lich hen, thoi gian hien tai.
*@
@page "/pos/{ShopId:guid}/beauty/doctor-schedule"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* === HEADER / TIEU DE === *@
    <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("beauty"))">
                <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
            </button>
            <span style="font-size:16px;font-weight:700;color:#A855F7;">
                <i data-lucide="stethoscope" style="width:20px;height:20px;display:inline;"></i>
                Lich Bac Si
            </span>
            <span style="font-size:13px;color:var(--pos-text-tertiary);">Hom nay, @DateTime.Now.ToString("dd/MM/yyyy")</span>
        </div>

        @* EN: Legend / VI: Chu thich *@
        <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(168,85,247,.3);"></span> Botox
            </span>
            <span style="display:flex;align-items:center;gap:4px;">
                <span style="width:10px;height:10px;border-radius:3px;background:rgba(236,72,153,.3);"></span> Filler
            </span>
            <span style="display:flex;align-items:center;gap:4px;">
                <span style="width:10px;height:10px;border-radius:3px;background:rgba(245,158,11,.3);"></span> Laser
            </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> Skincare
            </span>
        </div>
    </div>

    @* === SCHEDULE GRID / LUOI LICH === *@
    @if (_isLoading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Dang tai lich...
        </div>
    }
    else if (_loadError)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Khong the tai du lieu lich
        </div>
    }
    else
    {
    <div style="flex:1;overflow:auto;position:relative;">
        @* EN: Time header row / VI: Hang tieu de gio *@
        <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);">
                Bac si
            </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: Doctor rows / VI: Hang bac si *@
        @foreach (var doctor in _scheduleData)
        {
            <div style="display:flex;border-bottom:1px solid var(--pos-border-subtle);min-height:64px;">
                @* EN: Doctor name column / VI: Cot ten bac si *@
                <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:rgba(168,85,247,0.15);
                                display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#A855F7;flex-shrink:0;">
                        @doctor.Name[..1]
                    </div>
                    <div>
                        <div style="font-size:12px;font-weight:600;">@doctor.Name</div>
                        <div style="font-size:10px;color:var(--pos-text-tertiary);">@doctor.Role</div>
                    </div>
                </div>

                @* EN: Timeline with blocks / VI: Timeline voi khoi lich *@
                <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: Khoi lich hen *@
                    @foreach (var appt in doctor.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("beauty/treatment-plan"))">
                            <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: Chi bao thoi gian hien tai *@
        <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:#A855F7;z-index:5;">
            <div style="position:absolute;top:-4px;left:-4px;width:10px;height:10px;border-radius:50%;background:#A855F7;"></div>
        </div>
    </div>

    }

    @* === SUMMARY / TOM TAT === *@
    <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>Tong: <b>@_scheduleData.Sum(s => s.Appointments.Count)</b> lich hen</span>
        <span style="color:#A855F7;">Dang thuc hien: <b>@_inProgressCount</b></span>
        <span style="color:var(--pos-success);">Hoan thanh: <b>@_completedCount</b></span>
        <span style="color:var(--pos-text-tertiary);">Sap toi: <b>@_upcomingCount</b></span>
    </div>
</div>

@code {
    // EN: Loading state / VI: Trang thai tai
    private bool _isLoading = true;
    private bool _loadError;

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

    // EN: Summary counters / VI: Bo dem tom tat
    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: Tai nhan vien va lich hen 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: Loc lich hen hom nay
            var todayAppointments = appointments
                .Where(a => a.StartTime.Date == DateTime.Today)
                .ToList();

            // EN: Count by status / VI: Dem theo trang thai
            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: Nhom lich hen theo nhan vien
            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 ?? "Bac si");
            });

            // EN: Build schedule data — group by staff / VI: Xay dung du lieu lich — nhom theo nhan vien
            var grouped = todayAppointments
                .Where(a => a.StaffId.HasValue)
                .GroupBy(a => a.StaffId!.Value)
                .ToList();

            _scheduleData = new();

            foreach (var group in grouped)
            {
                var doctorName = staffMap.TryGetValue(group.Key, out var info) ? info.Name : group.Key.ToString()[..8];
                var doctorRole = staffMap.TryGetValue(group.Key, out var info2) ? info2.Role : "Bac si";

                var blocks = group.Select(a => new AppointmentBlock(
                    a.ResourceName ?? "Khach",
                    a.ResourceName ?? "Dich vu",
                    GuessServiceType(a.ResourceName),
                    a.StartTime.Hour,
                    a.StartTime.Minute,
                    (int)(a.EndTime - a.StartTime).TotalMinutes
                )).ToList();

                _scheduleData.Add(new DoctorScheduleRow(doctorName, doctorRole, blocks));
            }

            // EN: Add staff without appointments / VI: Them nhan vien chua co lich hen
            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 DoctorScheduleRow(name, s.Role ?? "Bac si", new()));
            }
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    // EN: Guess service type from name for color coding / VI: Doan loai dich vu tu ten de to mau
    private static string GuessServiceType(string? name)
    {
        if (name is null) return "Other";
        var lower = name.ToLower();
        if (lower.Contains("botox") || lower.Contains("tiem")) return "Botox";
        if (lower.Contains("filler") || lower.Contains("chat lan")) return "Filler";
        if (lower.Contains("laser") || lower.Contains("tri nam") || lower.Contains("triet long")) return "Laser";
        if (lower.Contains("skincare") || lower.Contains("da") || lower.Contains("duong")) return "Skincare";
        return "Other";
    }

    // EN: Beauty service type colors / VI: Mau loai dich vu tham my
    private static string GetServiceBg(string type) => type switch
    {
        "Botox" => "rgba(168,85,247,.15)",    // #A855F7 purple
        "Filler" => "rgba(236,72,153,.15)",    // #EC4899 pink
        "Laser" => "rgba(245,158,11,.15)",     // #F59E0B amber
        "Skincare" => "rgba(34,197,94,.15)",   // #22C55E green
        _ => "rgba(148,163,184,.15)"
    };

    private static string GetServiceColor(string type) => type switch
    {
        "Botox" => "#A855F7",
        "Filler" => "#EC4899",
        "Laser" => "#F59E0B",
        "Skincare" => "#22C55E",
        _ => "#94A3B8"
    };

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