@*
    EN: Follow-Up Management — Manage follow-up appointments after beauty treatments.
    VI: Quan Ly Tai Kham — Quan ly cac lich hen tai kham sau dieu tri tham my.
*@
@page "/pos/{ShopId:guid}/beauty/follow-up"
@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="calendar-heart" style="width:20px;height:20px;display:inline;"></i>
                Tai Kham
            </span>
        </div>

        @* EN: Summary stats / VI: Thong ke tom tat *@
        <div style="display:flex;gap:16px;font-size:12px;">
            <span style="display:flex;align-items:center;gap:4px;color:var(--pos-text-secondary);">
                Tong: <b>@_followUps.Count</b>
            </span>
            <span style="display:flex;align-items:center;gap:4px;color:var(--pos-danger);">
                Qua han: <b>@_followUps.Count(f => f.Status == "overdue")</b>
            </span>
            <span style="display:flex;align-items:center;gap:4px;color:var(--pos-success);">
                Hoan thanh hom nay: <b>@_followUps.Count(f => f.Status == "completed" && f.FollowUpDate.Date == DateTime.Today)</b>
            </span>
        </div>
    </div>

    @* === FILTER TABS / TAB LOC === *@
    <div style="display:flex;gap:8px;padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);flex-shrink:0;">
        @foreach (var tab in _tabs)
        {
            <button style="padding:8px 20px;border-radius:20px;border:1px solid @(_selectedTab == tab.Key ? "#A855F7" : "var(--pos-border-default)");
                           background:@(_selectedTab == tab.Key ? "#A855F7" : "var(--pos-bg-interactive)");
                           color:@(_selectedTab == tab.Key ? "#fff" : "var(--pos-text-primary)");
                           cursor:pointer;font-size:13px;font-weight:@(_selectedTab == tab.Key ? "600" : "400");"
                    @onclick="() => _selectedTab = tab.Key">
                @tab.Label
                @if (tab.Count > 0)
                {
                    <span style="margin-left:4px;font-size:11px;opacity:0.8;">(@tab.Count)</span>
                }
            </button>
        }
    </div>

    @* === FOLLOW-UP LIST / DANH SACH TAI KHAM === *@
    @if (_isLoading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Dang tai...
        </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
        </div>
    }
    else
    {
    <div style="flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;">
        @if (!FilteredFollowUps.Any())
        {
            <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:60px 0;color:var(--pos-text-tertiary);">
                <i data-lucide="calendar-heart" style="width:48px;height:48px;margin-bottom:12px;opacity:0.3;"></i>
                <div style="font-size:15px;font-weight:600;margin-bottom:4px;">Khong co lich tai kham</div>
                <div style="font-size:13px;">Khong co lich tai kham nao trong muc nay</div>
            </div>
        }

        @foreach (var followUp in FilteredFollowUps)
        {
            <div style="background:var(--pos-bg-elevated);border-radius:12px;padding:16px;border:1px solid var(--pos-border-subtle);
                        border-left:4px solid @GetStatusColor(followUp.Status);">
                <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:12px;">
                    <div>
                        <div style="font-size:15px;font-weight:700;color:var(--pos-text-primary);">@followUp.CustomerName</div>
                        <div style="font-size:13px;color:var(--pos-text-tertiary);">
                            <i data-lucide="phone" style="width:12px;height:12px;display:inline;"></i> @followUp.CustomerPhone
                        </div>
                    </div>
                    <span style="font-size:11px;padding:4px 12px;border-radius:20px;background:@GetStatusBg(followUp.Status);color:@GetStatusColor(followUp.Status);font-weight:600;">
                        @GetStatusLabel(followUp.Status)
                    </span>
                </div>

                <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px;font-size:13px;">
                    <div>
                        <span style="color:var(--pos-text-tertiary);">Dieu tri goc:</span>
                        <div style="font-weight:600;">@followUp.TreatmentName</div>
                    </div>
                    <div>
                        <span style="color:var(--pos-text-tertiary);">Ngay dieu tri:</span>
                        <div style="font-weight:600;">@followUp.TreatmentDate.ToString("dd/MM/yyyy")</div>
                    </div>
                    <div>
                        <span style="color:var(--pos-text-tertiary);">Ngay tai kham:</span>
                        <div style="font-weight:600;color:@(followUp.FollowUpDate.Date < DateTime.Today && followUp.Status != "completed" ? "var(--pos-danger)" : "var(--pos-text-primary)");">
                            @followUp.FollowUpDate.ToString("dd/MM/yyyy")
                            @if (followUp.FollowUpDate.Date < DateTime.Today && followUp.Status != "completed")
                            {
                                <span style="font-size:11px;"> (qua han)</span>
                            }
                        </div>
                    </div>
                    <div>
                        <span style="color:var(--pos-text-tertiary);">Bac si:</span>
                        <div style="font-weight:600;">@followUp.DoctorName</div>
                    </div>
                </div>

                @* EN: Action buttons / VI: Nut hanh dong *@
                <div style="display:flex;gap:8px;">
                    <button style="flex:1;padding:8px;border-radius:8px;border:1px solid var(--pos-border-default);background:var(--pos-bg-interactive);color:var(--pos-text-primary);cursor:pointer;font-size:12px;font-weight:600;"
                            @onclick="() => CallCustomer(followUp)">
                        <i data-lucide="phone" style="width:14px;height:14px;display:inline;"></i> Goi
                    </button>
                    <button style="flex:1;padding:8px;border-radius:8px;border:1px solid #A855F7;background:rgba(168,85,247,0.1);color:#A855F7;cursor:pointer;font-size:12px;font-weight:600;"
                            @onclick="() => Reschedule(followUp)">
                        <i data-lucide="calendar" style="width:14px;height:14px;display:inline;"></i> Doi lich
                    </button>
                    <button style="flex:1;padding:8px;border-radius:8px;border:none;background:var(--pos-success);color:#fff;cursor:pointer;font-size:12px;font-weight:600;"
                            @onclick="() => MarkComplete(followUp)">
                        <i data-lucide="check" style="width:14px;height:14px;display:inline;"></i> Hoan thanh
                    </button>
                </div>
            </div>
        }
    </div>
    }
</div>

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

    private string _selectedTab = "today";
    private List<FollowUpItem> _followUps = new();

    private record TabItem(string Key, string Label, int Count);
    private TabItem[] _tabs = Array.Empty<TabItem>();

    private IEnumerable<FollowUpItem> FilteredFollowUps => _selectedTab switch
    {
        "today" => _followUps.Where(f => f.FollowUpDate.Date == DateTime.Today),
        "week" => _followUps.Where(f => f.FollowUpDate.Date >= DateTime.Today && f.FollowUpDate.Date <= DateTime.Today.AddDays(7)),
        "overdue" => _followUps.Where(f => f.FollowUpDate.Date < DateTime.Today && f.Status != "completed"),
        _ => _followUps
    };

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

        try
        {
            var appointments = await DataService.GetAppointmentsAsync(ShopId);

            // EN: Map appointments to follow-up context / VI: Map lich hen sang ngu canh tai kham
            _followUps = appointments
                .Where(a => a.Status?.ToLower() != "cancelled")
                .Select(a =>
                {
                    var followUpDate = a.EndTime.AddDays(14); // EN: Default 2-week follow-up / VI: Mac dinh tai kham sau 2 tuan
                    var status = DetermineFollowUpStatus(a, followUpDate);

                    return new FollowUpItem
                    {
                        Id = a.Id,
                        CustomerName = a.ResourceName ?? "Khach hang",
                        CustomerPhone = "0901-xxx-xxx",
                        TreatmentName = a.ResourceName ?? "Dich vu tham my",
                        TreatmentDate = a.StartTime,
                        FollowUpDate = followUpDate,
                        DoctorName = "Bac si",
                        Status = status
                    };
                })
                .OrderBy(f => f.FollowUpDate)
                .ToList();

            UpdateTabs();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private static string DetermineFollowUpStatus(WebClientTpos.Client.Services.PosDataService.AppointmentInfo a, DateTime followUpDate)
    {
        if (a.Status?.ToLower() == "completed" && followUpDate.Date <= DateTime.Today)
            return "completed";
        if (followUpDate.Date < DateTime.Today)
            return "overdue";
        if (followUpDate.Date == DateTime.Today)
            return "scheduled";
        return "scheduled";
    }

    private void UpdateTabs()
    {
        _tabs = new[]
        {
            new TabItem("today", "Hom nay", _followUps.Count(f => f.FollowUpDate.Date == DateTime.Today)),
            new TabItem("week", "Tuan nay", _followUps.Count(f => f.FollowUpDate.Date >= DateTime.Today && f.FollowUpDate.Date <= DateTime.Today.AddDays(7))),
            new TabItem("overdue", "Qua han", _followUps.Count(f => f.FollowUpDate.Date < DateTime.Today && f.Status != "completed")),
        };
    }

    private void CallCustomer(FollowUpItem followUp)
    {
        followUp.Status = "contacted";
        UpdateTabs();
    }

    private void Reschedule(FollowUpItem followUp)
    {
        followUp.FollowUpDate = followUp.FollowUpDate.AddDays(7);
        followUp.Status = "scheduled";
        UpdateTabs();
    }

    private void MarkComplete(FollowUpItem followUp)
    {
        followUp.Status = "completed";
        UpdateTabs();
    }

    private static string GetStatusColor(string status) => status switch
    {
        "completed" => "#22C55E",
        "contacted" => "#3B82F6",
        "scheduled" => "#A855F7",
        "overdue" => "#EF4444",
        "missed" => "#EF4444",
        _ => "#94A3B8"
    };

    private static string GetStatusBg(string status) => status switch
    {
        "completed" => "rgba(34,197,94,0.1)",
        "contacted" => "rgba(59,130,246,0.1)",
        "scheduled" => "rgba(168,85,247,0.1)",
        "overdue" => "rgba(239,68,68,0.1)",
        "missed" => "rgba(239,68,68,0.1)",
        _ => "rgba(148,163,184,0.1)"
    };

    private static string GetStatusLabel(string status) => status switch
    {
        "completed" => "Hoan thanh",
        "contacted" => "Da lien he",
        "scheduled" => "Da hen",
        "overdue" => "Qua han",
        "missed" => "Bo lo",
        _ => "Chua xac dinh"
    };

    private class FollowUpItem
    {
        public Guid Id { get; set; }
        public string CustomerName { get; set; } = "";
        public string CustomerPhone { get; set; } = "";
        public string TreatmentName { get; set; } = "";
        public DateTime TreatmentDate { get; set; }
        public DateTime FollowUpDate { get; set; }
        public string DoctorName { get; set; } = "";
        public string Status { get; set; } = "scheduled";
    }
}
