@*
    EN: Karaoke Peak Warning — Peak hours pricing comparison, room type multipliers, cost estimator.
        Loads real room data from API to build pricing tiers dynamically.
    VI: Canh bao gio cao diem Karaoke — So sanh gia gio cao diem, he so phong, uoc tinh chi phi.
        Tai du lieu phong that tu API de xay dung bang gia dong.
*@
@page "/pos/{ShopId:guid}/karaoke/peak-warning"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService
@implements IDisposable

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* === HEADER / TIEU DE === *@
    <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);flex-shrink:0;">
        <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("karaoke"))">
            <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
        </button>
        <span style="font-size:16px;font-weight:700;">
            <i data-lucide="alert-triangle" style="width:18px;height:18px;display:inline;color:var(--pos-warning);"></i>
            Gio cao diem
        </span>
    </div>

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Dang tai...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Khong the tai du lieu
        </div>
    }
    else
    {
    <div style="flex:1;overflow-y:auto;padding:16px;">
        @* === CURRENT TIME / THOI GIAN HIEN TAI === *@
        <div style="background:linear-gradient(135deg,rgba(245,158,11,.2),rgba(239,68,68,.15));
                    border-radius:var(--pos-radius);padding:24px;margin-bottom:16px;text-align:center;
                    border:1px solid rgba(245,158,11,.3);">
            <div style="font-size:12px;font-weight:600;color:var(--pos-warning);text-transform:uppercase;letter-spacing:1px;">
                KHUNG GIO HIEN TAI
            </div>
            <div style="font-size:36px;font-weight:700;color:var(--pos-warning);margin:8px 0;">
                @_currentTime.ToString("HH:mm") — @GetDayOfWeekVi(_currentTime.DayOfWeek)
            </div>
            <div style="font-size:13px;color:var(--pos-text-secondary);">
                Dang ap dung gia <b style="color:var(--pos-warning);">@(ActiveRate?.Label ?? "thong thuong")</b>
            </div>
        </div>

        @* === PRICING TABLE / BANG GIA === *@
        <div style="margin-bottom:20px;">
            <div style="font-size:14px;font-weight:600;margin-bottom:12px;">Bang gia theo khung gio (Standard)</div>
            <div style="display:flex;flex-direction:column;gap:8px;">
                @foreach (var rate in _pricingRates)
                {
                    <div style="display:flex;align-items:center;gap:12px;padding:14px 16px;
                                background:@(rate.IsActive ? "rgba(245,158,11,.12)" : "var(--pos-bg-elevated)");
                                border-radius:var(--pos-radius);
                                border:1px solid @(rate.IsActive ? "var(--pos-warning)" : "var(--pos-border-subtle)");">
                        <div style="flex:1;">
                            <div style="font-size:13px;font-weight:600;color:@(rate.IsActive ? "var(--pos-warning)" : "var(--pos-text-primary)");">
                                @rate.Label
                            </div>
                            <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">@rate.TimeRange</div>
                        </div>
                        <div style="text-align:right;">
                            <div style="font-size:14px;font-weight:700;color:@(rate.IsActive ? "var(--pos-warning)" : "var(--pos-text-primary)");">
                                @FormatPrice(rate.Price)/gio
                            </div>
                            <div style="font-size:11px;color:var(--pos-text-tertiary);">x@rate.Multiplier.ToString("0.0")</div>
                        </div>
                        @if (rate.IsActive)
                        {
                            <span style="font-size:11px;padding:3px 8px;border-radius:6px;font-weight:600;
                                         background:rgba(245,158,11,.2);color:var(--pos-warning);">Hien tai</span>
                        }
                    </div>
                }
            </div>
        </div>

        @* === ROOM TYPE SELECTOR / CHON LOAI PHONG === *@
        <div style="margin-bottom:20px;">
            <div style="font-size:14px;font-weight:600;margin-bottom:12px;">Loai phong</div>
            <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;">
                @foreach (var room in _roomTypes)
                {
                    <button @onclick="() => _selectedRoomType = room"
                            style="padding:16px;border-radius:var(--pos-radius);text-align:center;cursor:pointer;
                                   background:@(_selectedRoomType?.Name == room.Name ? "var(--pos-orange-primary)" : "var(--pos-bg-elevated)");
                                   color:@(_selectedRoomType?.Name == room.Name ? "#FFF" : "var(--pos-text-primary)");
                                   border:1px solid @(_selectedRoomType?.Name == room.Name ? "var(--pos-orange-primary)" : "var(--pos-border-subtle)");">
                        <div style="font-size:14px;font-weight:700;">@room.Name</div>
                        <div style="font-size:12px;margin-top:4px;opacity:0.7;">@FormatPrice(room.BaseRate)/gio</div>
                    </button>
                }
            </div>
        </div>

        @* === COST ESTIMATOR / UOC TINH CHI PHI === *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;">
            <div style="font-size:14px;font-weight:600;margin-bottom:12px;">Uoc tinh chi phi</div>
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
                <span style="font-size:13px;color:var(--pos-text-secondary);">So gio:</span>
                <button style="width:36px;height:36px;border-radius:8px;border:1px solid var(--pos-border-default);
                               background:transparent;color:var(--pos-text-primary);cursor:pointer;font-size:16px;"
                        @onclick="() => _estimateHours = Math.Max(1, _estimateHours - 1)">-</button>
                <span style="font-size:20px;font-weight:700;min-width:30px;text-align:center;">@_estimateHours</span>
                <button style="width:36px;height:36px;border-radius:8px;border:1px solid var(--pos-border-default);
                               background:transparent;color:var(--pos-text-primary);cursor:pointer;font-size:16px;"
                        @onclick="() => _estimateHours++">+</button>
                <span style="font-size:13px;color:var(--pos-text-tertiary);">gio</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px;">
                <span style="color:var(--pos-text-secondary);">Gia hien tai (@(_selectedRoomType?.Name ?? "Standard"))</span>
                <span>@FormatPrice(CurrentRatePrice)/gio</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px;">
                <span style="color:var(--pos-text-secondary);">So gio</span>
                <span>@_estimateHours gio</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:16px;font-weight:700;
                        padding-top:10px;border-top:1px solid var(--pos-border-subtle);">
                <span>Tong uoc tinh</span>
                <span style="color:var(--pos-orange-primary);">@FormatPrice(CurrentRatePrice * _estimateHours)</span>
            </div>
        </div>
    </div>

    @* === CONFIRM BUTTON / NUT XAC NHAN === *@
    <div style="padding:12px 16px;border-top:1px solid var(--pos-border-subtle);flex-shrink:0;">
        <button style="width:100%;padding:16px;border-radius:var(--pos-radius);background:var(--pos-orange-primary);
                       border:none;color:#FFF;cursor:pointer;font-size:15px;font-weight:700;"
                @onclick="@(() => NavigateTo("karaoke/room-select"))">
            <i data-lucide="check" style="width:18px;height:18px;display:inline;"></i> Xac nhan gia
        </button>
    </div>
    }
</div>

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

    // EN: Current time, updated every minute / VI: Thoi gian hien tai, cap nhat moi phut
    private DateTime _currentTime = DateTime.Now;
    private Timer? _timer;

    // EN: Estimate hours / VI: So gio uoc tinh
    private int _estimateHours = 2;

    // EN: Pricing rates built from room data / VI: Bang gia xay dung tu du lieu phong
    private List<PricingRate> _pricingRates = new();

    // EN: Room types grouped from API data / VI: Loai phong nhom tu du lieu API
    private List<RoomTypeInfo> _roomTypes = new();
    private RoomTypeInfo? _selectedRoomType;

    // EN: Active pricing rate based on current hour / VI: Muc gia dang ap dung theo gio hien tai
    private PricingRate? ActiveRate => _pricingRates.FirstOrDefault(r => r.IsActive);

    // EN: Current rate price adjusted for room type / VI: Gia hien tai theo loai phong
    private decimal CurrentRatePrice
    {
        get
        {
            var activeRate = ActiveRate ?? _pricingRates.FirstOrDefault();
            if (activeRate == null || _selectedRoomType == null) return 0;
            return _selectedRoomType.BaseRate * activeRate.Multiplier;
        }
    }

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

        try
        {
            var tables = await DataService.GetTablesAsync(ShopId);

            // EN: Group rooms by zone/type to derive pricing tiers
            // VI: Nhom phong theo khu/loai de xay dung muc gia
            var groups = tables
                .GroupBy(t => t.Zone ?? "Standard")
                .Select(g => new RoomTypeInfo(
                    g.Key,
                    g.Average(t => t.HourlyRate) > 0 ? Math.Round(g.Average(t => t.HourlyRate)) : 100_000m
                ))
                .OrderBy(r => r.BaseRate)
                .ToList();

            _roomTypes = groups.Any() ? groups : new List<RoomTypeInfo>
            {
                new("Standard", 100_000),
                new("Deluxe", 150_000),
                new("VIP", 200_000),
            };

            _selectedRoomType = _roomTypes.First();

            // EN: Build pricing rates based on time-of-day with base rate from cheapest room type
            // VI: Xay dung bang gia theo khung gio voi gia co ban tu loai phong re nhat
            var baseRate = _roomTypes.Min(r => r.BaseRate);
            if (baseRate <= 0) baseRate = 100_000;

            BuildPricingRates(baseRate);

            // EN: Start clock timer / VI: Bat dau dong ho
            _timer = new Timer(_ =>
            {
                _currentTime = DateTime.Now;
                BuildPricingRates(baseRate);
                InvokeAsync(StateHasChanged);
            }, null, TimeSpan.FromSeconds(60 - DateTime.Now.Second), TimeSpan.FromMinutes(1));
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void BuildPricingRates(decimal baseRate)
    {
        var hour = _currentTime.Hour;
        var dow = _currentTime.DayOfWeek;
        var isWeekend = dow == DayOfWeek.Saturday || dow == DayOfWeek.Sunday;

        _pricingRates = new List<PricingRate>
        {
            new("Gio thuong",      "T2-T5, 10:00-17:00", baseRate * 1.0m, 1.0m, !isWeekend && hour >= 10 && hour < 17),
            new("Gio cao diem",    "T2-T5, 17:00-23:00", baseRate * 1.5m, 1.5m, !isWeekend && hour >= 17 && hour < 23),
            new("Cuoi tuan",       "T6-CN",              baseRate * 1.8m, 1.8m, isWeekend),
            new("Le/Tet",          "Ngay le, Tet",       baseRate * 2.5m, 2.5m, false),
        };

        // EN: Fallback: if no rate is active (e.g., before 10AM on weekday), activate "Gio thuong"
        // VI: Du phong: neu khong co muc gia nao active, kich hoat "Gio thuong"
        if (!_pricingRates.Any(r => r.IsActive))
        {
            _pricingRates[0] = _pricingRates[0] with { IsActive = true };
        }
    }

    private static string GetDayOfWeekVi(DayOfWeek dow) => dow switch
    {
        DayOfWeek.Monday => "Thu 2",
        DayOfWeek.Tuesday => "Thu 3",
        DayOfWeek.Wednesday => "Thu 4",
        DayOfWeek.Thursday => "Thu 5",
        DayOfWeek.Friday => "Thu 6",
        DayOfWeek.Saturday => "Thu 7",
        DayOfWeek.Sunday => "CN",
        _ => ""
    };

    public void Dispose()
    {
        _timer?.Dispose();
    }

    private record PricingRate(string Label, string TimeRange, decimal Price, decimal Multiplier, bool IsActive);
    private record RoomTypeInfo(string Name, decimal BaseRate);
}
