@page "/club/features"
@attribute [Authorize(Roles = "Administrator")]

@using CMSMicroservice.Protobuf.Protos.Configuration
@using CMSMicroservice.Protobuf.Protos.ClubMembership
@using BackOffice.Pages.AutoComplete

@inject ConfigurationContract.ConfigurationContractClient ConfigClient
@inject ClubMembershipContract.ClubMembershipContractClient ClubClient

<div>
    <MudText Typo="Typo.h5" Class="mb-3">فیچرهای باشگاه</MudText>

    @* ── G9: راهنمای ماتریس فیچر (Q28) ── *@
    <MudAlert Severity="Severity.Info" Variant="Variant.Text" Dense="true" Class="mb-3" Icon="@Icons.Material.Filled.Info">
        فیچرهای تیک‌خورده برای خریداران این پکیج فعال می‌شود. تغییر فیچرها روی کاربران فعلی بلافاصله اعمال می‌شود.
    </MudAlert>

    <MudTabs Elevation="0" Rounded="true" Border="true" ApplyEffectsToContainer="true"
             PanelClass="pt-4" @bind-ActivePanelIndex="_activeTab">

        @* ── تب اول: لیست فیچرها ── *@
        <MudTabPanel Text="فیچرهای تعریف‌شده" Icon="@Icons.Material.Filled.Star">
            @if (_loadingFeatures)
            {
                <MudProgressLinear Color="Color.Primary" Indeterminate="true" />
            }
            else if (_features.Count == 0)
            {
                <MudAlert Severity="Severity.Info" Variant="Variant.Text">فیچری تعریف نشده است.</MudAlert>
            }
            else
            {
                <MudGrid Spacing="2">
                    @foreach (var feature in _features)
                    {
                        <MudItem xs="12" sm="6" md="4">
                            <MudPaper Class="pa-3 rounded-lg" Outlined="true">
                                <MudStack Spacing="1">
                                    <MudStack Row="true" AlignItems="AlignItems.Center" Justify="Justify.SpaceBetween">
                                        <MudText Typo="Typo.subtitle1"><strong>@feature.Title</strong></MudText>
                                        <MudChip T="string" Size="Size.Small"
                                                 Color="@(feature.IsEnabled ? Color.Success : Color.Error)">
                                            @(feature.IsEnabled ? "فعال" : "غیرفعال")
                                        </MudChip>
                                    </MudStack>
                                    @if (!string.IsNullOrWhiteSpace(feature.Description))
                                    {
                                        <MudText Typo="Typo.body2" Color="Color.Secondary">@feature.Description</MudText>
                                    }
                                    <MudText Typo="Typo.caption">ترتیب: @feature.DisplayOrder</MudText>
                                </MudStack>
                            </MudPaper>
                        </MudItem>
                    }
                </MudGrid>
            }
        </MudTabPanel>

        @* ── تب دوم: فیچرهای کاربران ── *@
        <MudTabPanel Text="فیچرهای کاربران" Icon="@Icons.Material.Filled.PeopleAlt">
            <MudStack Row="true" Spacing="2" AlignItems="AlignItems.Center" Class="mb-3">
                <UserAutoComplete Label="جستجوی کاربر" @bind-SelectedUserId="_featureFilterUserId" />
                <MudButton Variant="Variant.Filled" Color="Color.Primary"
                           StartIcon="@Icons.Material.Filled.Search"
                           OnClick="LoadUserFeatures">جستجو</MudButton>
            </MudStack>

            @if (_loadingUserFeatures)
            {
                <MudProgressLinear Color="Color.Primary" Indeterminate="true" />
            }
            else if (_featureFilterUserId == null || _featureFilterUserId == 0)
            {
                <MudAlert Severity="Severity.Info" Variant="Variant.Text">لطفاً یک کاربر انتخاب کنید.</MudAlert>
            }
            else if (_userFeatures.Count == 0)
            {
                <MudAlert Severity="Severity.Info" Variant="Variant.Text">فیچری برای این کاربر یافت نشد.</MudAlert>
            }
            else
            {
                <MudDataGrid T="UserClubFeatureModel" Items="_userFeatures"
                             Hover="true" Dense="true"
                             Height="calc(100vh - 340px)">
                    <Columns>
                        <PropertyColumn Property="x => x.Id" Title="شناسه" />
                        <PropertyColumn Property="x => x.FeatureTitle" Title="عنوان فیچر" />
                        <TemplateColumn Title="توضیحات">
                            <CellTemplate>
                                <MudText Typo="Typo.body2">@(string.IsNullOrWhiteSpace(context.Item.FeatureDescription) ? "—" : context.Item.FeatureDescription)</MudText>
                            </CellTemplate>
                        </TemplateColumn>
                        <TemplateColumn Title="وضعیت">
                            <CellTemplate>
                                <MudSwitch T="bool" Value="context.Item.IsActive"
                                           Color="Color.Success"
                                           ValueChanged="@(val => ToggleFeature(context.Item, val))" />
                            </CellTemplate>
                        </TemplateColumn>
                        <TemplateColumn Title="تاریخ اختصاص">
                            <CellTemplate>
                                @if (context.Item.GrantedAt != null)
                                {
                                    @context.Item.GrantedAt.ToDateTime().ToLocalTime().MiladiToJalali()
                                }
                            </CellTemplate>
                        </TemplateColumn>
                        <PropertyColumn Property="x => x.Notes" Title="یادداشت" />
                    </Columns>
                    <NoRecordsContent>
                        <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text" Class="my-4">موردی یافت نشد.</MudAlert>
                    </NoRecordsContent>
                    <PagerContent>
                        <MudDataGridPager T="UserClubFeatureModel" PageSizeOptions="@(new int[] { 20, 50, 100 })"
                                          InfoFormat="سطر {first_item} تا {last_item} از {all_items}"
                                          RowsPerPageString="تعداد در صفحه" />
                    </PagerContent>
                </MudDataGrid>
            }
        </MudTabPanel>
    </MudTabs>
</div>

@code {
    private int _activeTab;
    private bool _loadingFeatures;
    private bool _loadingUserFeatures;

    // Features tab
    private List<ClubFeatureModel> _features = new();

    // User features tab
    private long? _featureFilterUserId;
    private List<UserClubFeatureModel> _userFeatures = new();

    protected override async Task OnInitializedAsync()
    {
        await LoadFeatures();
    }

    private async Task LoadFeatures()
    {
        _loadingFeatures = true;
        try
        {
            var result = await ConfigClient.GetClubFeaturesAsync(new Google.Protobuf.WellKnownTypes.Empty());
            _features = result?.Features?.ToList() ?? new();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری فیچرها: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loadingFeatures = false;
        }
    }

    private async Task LoadUserFeatures()
    {
        if (_featureFilterUserId == null || _featureFilterUserId == 0) return;

        _loadingUserFeatures = true;
        try
        {
            var result = await ClubClient.GetUserClubFeaturesAsync(new GetUserClubFeaturesRequest
            {
                UserId = _featureFilterUserId.Value
            });
            _userFeatures = result?.Features?.ToList() ?? new();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loadingUserFeatures = false;
        }
    }

    private async Task ToggleFeature(UserClubFeatureModel feature, bool isActive)
    {
        try
        {
            await ClubClient.ToggleUserClubFeatureAsync(new ToggleUserClubFeatureRequest
            {
                UserId = feature.UserId,
                ClubFeatureId = feature.ClubFeatureId,
                IsActive = isActive
            });

            feature.IsActive = isActive;
            Snackbar.Add($"فیچر «{feature.FeatureTitle}» {(isActive ? "فعال" : "غیرفعال")} شد", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
    }
}
