@page "/network/user-info/{UserId:long}"
@using CMSMicroservice.Protobuf.Protos.NetworkMembership
@attribute [Authorize]


<div>
    <MudBreadcrumbs Items="_breadcrumbs" Class="mb-4"></MudBreadcrumbs>

    @if (_isLoading)
    {
        <MudPaper Class="pa-8 d-flex justify-center">
            <MudProgressCircular Color="Color.Primary" Size="Size.Large" Indeterminate="true" />
        </MudPaper>
    }
    else if (_userInfo != null)
    {
        <MudGrid>
            <!-- اطلاعات کاربر -->
            <MudItem xs="12" md="6">
                <MudCard>
                    <MudCardHeader>
                        <CardHeaderContent>
                            <MudText Typo="Typo.h6">اطلاعات کاربر</MudText>
                        </CardHeaderContent>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudSimpleTable Dense="true">
                            <tbody>
                                <tr>
                                    <td><strong>شناسه:</strong></td>
                                    <td>@_userInfo.UserId</td>
                                </tr>
                                <tr>
                                    <td><strong>نام کاربر:</strong></td>
                                    <td>@_userInfo.UserName</td>
                                </tr>
                                <tr>
                                    <td><strong>موبایل:</strong></td>
                                    <td>
                                        @_userInfo.Mobile
                                        @if (_userInfo.IsMobileVerified)
                                        {
                                            <MudChip T="string" Color="Color.Success" Size="Size.Small" Icon="@Icons.Material.Filled.Verified">تایید شده</MudChip>
                                        }
                                    </td>
                                </tr>
                                @if (!string.IsNullOrEmpty(_userInfo.Email))
                                {
                                    <tr>
                                        <td><strong>ایمیل:</strong></td>
                                        <td>@_userInfo.Email</td>
                                    </tr>
                                }
                                @if (!string.IsNullOrEmpty(_userInfo.NationalCode))
                                {
                                    <tr>
                                        <td><strong>کد ملی:</strong></td>
                                        <td>@_userInfo.NationalCode</td>
                                    </tr>
                                }
                                <tr>
                                    <td><strong>کد ارجاع:</strong></td>
                                    <td><MudChip T="string" Color="Color.Info" Size="Size.Small">@_userInfo.ReferralCode</MudChip></td>
                                </tr>
                                <tr>
                                    <td><strong>موقعیت:</strong></td>
                                    <td>
                                        <MudChip T="string" 
                                                Color="@(_userInfo.NetworkLeg == 0 ? Color.Success : Color.Warning)" 
                                                Size="Size.Small">
                                            @(_userInfo.NetworkLeg == 0 ? "چپ" : "راست")
                                        </MudChip>
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>تاریخ عضویت:</strong></td>
                                    <td>@PersianDateTime.ConvertToPersianDateTime(_userInfo.JoinedAt.ToDateTime().ToLocalTime())</td>
                                </tr>
                            </tbody>
                        </MudSimpleTable>
                    </MudCardContent>
                </MudCard>
            </MudItem>

            <!-- ساختار شبکه -->
            <MudItem xs="12" md="6">
                <MudCard>
                    <MudCardHeader>
                        <CardHeaderContent>
                            <MudText Typo="Typo.h6">ساختار شبکه</MudText>
                        </CardHeaderContent>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudSimpleTable Dense="true">
                            <tbody>
                                @if (_userInfo.ParentId.HasValue && _userInfo.ParentId.Value > 0)
                                {
                                    <tr>
                                        <td><strong>والد:</strong></td>
                                        <td>
                                            <MudStack Spacing="1">
                                                <MudButton Size="Size.Small" 
                                                          Variant="Variant.Text" 
                                                          Color="Color.Primary"
                                                          OnClick="@(() => NavigateToUser(_userInfo.ParentId))">
                                                    @_userInfo.ParentName (ID: @_userInfo.ParentId)
                                                </MudButton>
                                                <MudText Typo="Typo.caption" Color="Color.Secondary">@_userInfo.ParentMobile</MudText>
                                            </MudStack>
                                        </td>
                                    </tr>
                                }
                                <tr>
                                    <td><strong>زیرمجموعه چپ:</strong></td>
                                    <td>
                                        @if (_userInfo.LeftChildId > 0)
                                        {
                                            <MudStack Spacing="1">
                                                <MudButton Size="Size.Small" 
                                                          Variant="Variant.Text" 
                                                          Color="Color.Success"
                                                          OnClick="@(() => NavigateToUser(_userInfo.LeftChildId))">
                                                    @_userInfo.LeftChildName (ID: @_userInfo.LeftChildId)
                                                </MudButton>
                                                <MudText Typo="Typo.caption" Color="Color.Secondary">@_userInfo.LeftChildMobile</MudText>
                                                @if (_userInfo.LeftChildJoinedAt != null)
                                                {
                                                    <MudText Typo="Typo.caption" Color="Color.Secondary">
                                                        عضو شده: @PersianDateTime.ConvertToPersianDate(_userInfo.LeftChildJoinedAt.ToDateTime().ToLocalTime())
                                                    </MudText>
                                                }
                                            </MudStack>
                                        }
                                        else
                                        {
                                            <MudText Color="Color.Secondary">خالی</MudText>
                                        }
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>زیرمجموعه راست:</strong></td>
                                    <td>
                                        @if (_userInfo.RightChildId > 0)
                                        {
                                            <MudStack Spacing="1">
                                                <MudButton Size="Size.Small" 
                                                          Variant="Variant.Text" 
                                                          Color="Color.Warning"
                                                          OnClick="@(() => NavigateToUser(_userInfo.RightChildId))">
                                                    @_userInfo.RightChildName (ID: @_userInfo.RightChildId)
                                                </MudButton>
                                                <MudText Typo="Typo.caption" Color="Color.Secondary">@_userInfo.RightChildMobile</MudText>
                                                @if (_userInfo.RightChildJoinedAt != null)
                                                {
                                                    <MudText Typo="Typo.caption" Color="Color.Secondary">
                                                        عضو شده: @PersianDateTime.ConvertToPersianDate(_userInfo.RightChildJoinedAt.ToDateTime().ToLocalTime())
                                                    </MudText>
                                                }
                                            </MudStack>
                                        }
                                        else
                                        {
                                            <MudText Color="Color.Secondary">خالی</MudText>
                                        }
                                    </td>
                                </tr>
                            </tbody>
                        </MudSimpleTable>
                    </MudCardContent>
                </MudCard>
            </MudItem>

            <!-- آمار شبکه -->
            <MudItem xs="12">
                <MudCard>
                    <MudCardHeader>
                        <CardHeaderContent>
                            <MudText Typo="Typo.h6">آمار کامل شبکه</MudText>
                        </CardHeaderContent>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudGrid>
                            <MudItem xs="12" sm="6" md="3">
                                <MudPaper Class="pa-4" Elevation="0">
                                    <MudStack Spacing="2">
                                        <MudIcon Icon="@Icons.Material.Filled.AccountTree" Color="Color.Primary" Size="Size.Large" />
                                        <MudText Typo="Typo.h4">@_userInfo.TotalNetworkSize</MudText>
                                        <MudText Typo="Typo.body2" Color="Color.Secondary">کل اعضای شبکه</MudText>
                                    </MudStack>
                                </MudPaper>
                            </MudItem>
                            <MudItem xs="12" sm="6" md="3">
                                <MudPaper Class="pa-4" Elevation="0">
                                    <MudStack Spacing="2">
                                        <MudIcon Icon="@Icons.Material.Filled.TrendingUp" Color="Color.Success" Size="Size.Large" />
                                        <MudText Typo="Typo.h4">@_userInfo.TotalLeftLegMembers</MudText>
                                        <MudText Typo="Typo.body2" Color="Color.Secondary">اعضای شاخه چپ</MudText>
                                    </MudStack>
                                </MudPaper>
                            </MudItem>
                            <MudItem xs="12" sm="6" md="3">
                                <MudPaper Class="pa-4" Elevation="0">
                                    <MudStack Spacing="2">
                                        <MudIcon Icon="@Icons.Material.Filled.TrendingDown" Color="Color.Warning" Size="Size.Large" />
                                        <MudText Typo="Typo.h4">@_userInfo.TotalRightLegMembers</MudText>
                                        <MudText Typo="Typo.body2" Color="Color.Secondary">اعضای شاخه راست</MudText>
                                    </MudStack>
                                </MudPaper>
                            </MudItem>
                            <MudItem xs="12" sm="6" md="3">
                                <MudPaper Class="pa-4" Elevation="0">
                                    <MudStack Spacing="2">
                                        <MudIcon Icon="@Icons.Material.Filled.Layers" Color="Color.Info" Size="Size.Large" />
                                        <MudText Typo="Typo.h4">@_userInfo.MaxNetworkDepth</MudText>
                                        <MudText Typo="Typo.body2" Color="Color.Secondary">حداکثر عمق شبکه</MudText>
                                    </MudStack>
                                </MudPaper>
                            </MudItem>
                            <MudItem xs="12" sm="6" md="3">
                                <MudPaper Class="pa-4" Elevation="0">
                                    <MudStack Spacing="2">
                                        <MudIcon Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success" Size="Size.Large" />
                                        <MudText Typo="Typo.h4">@_userInfo.ActiveMembersInNetwork</MudText>
                                        <MudText Typo="Typo.body2" Color="Color.Secondary">اعضای فعال (پکیج خریداری)</MudText>
                                    </MudStack>
                                </MudPaper>
                            </MudItem>
                            <MudItem xs="12" sm="6" md="3">
                                <MudPaper Class="pa-4" Elevation="0">
                                    <MudStack Spacing="2">
                                        <MudIcon Icon="@Icons.Material.Filled.Cancel" Color="Color.Error" Size="Size.Large" />
                                        <MudText Typo="Typo.h4">@_userInfo.InactiveMembersInNetwork</MudText>
                                        <MudText Typo="Typo.body2" Color="Color.Secondary">اعضای غیرفعال</MudText>
                                    </MudStack>
                                </MudPaper>
                            </MudItem>
                        </MudGrid>
                    </MudCardContent>
                </MudCard>
            </MudItem>

            <!-- آمار مالی -->
            <MudItem xs="12" md="6">
                <MudCard>
                    <MudCardHeader>
                        <CardHeaderContent>
                            <MudText Typo="Typo.h6">آمار مالی و کمیسیون</MudText>
                        </CardHeaderContent>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudSimpleTable Dense="true">
                            <tbody>
                                <tr>
                                    <td><strong>کل کمیسیون کسب شده:</strong></td>
                                    <td>
                                        <MudText Typo="Typo.body1" Color="Color.Primary">
                                            <strong>@_userInfo.TotalEarnedCommission.ToString("N0") تومان</strong>
                                        </MudText>
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>کمیسیون پرداخت شده:</strong></td>
                                    <td>
                                        <MudText Typo="Typo.body1" Color="Color.Success">
                                            @_userInfo.TotalPaidCommission.ToString("N0") تومان
                                        </MudText>
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>کمیسیون در انتظار:</strong></td>
                                    <td>
                                        <MudText Typo="Typo.body1" Color="Color.Warning">
                                            @_userInfo.PendingCommission.ToString("N0") تومان
                                        </MudText>
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>تعداد بالانس کسب شده:</strong></td>
                                    <td>
                                        <MudChip T="string" Color="Color.Info" Size="Size.Small">
                                            @_userInfo.TotalBalancesEarned بالانس
                                        </MudChip>
                                    </td>
                                </tr>
                            </tbody>
                        </MudSimpleTable>
                    </MudCardContent>
                </MudCard>
            </MudItem>

            <!-- وضعیت پکیج و دایا -->
            <MudItem xs="12" md="6">
                <MudCard>
                    <MudCardHeader>
                        <CardHeaderContent>
                            <MudText Typo="Typo.h6">وضعیت پکیج و دایا</MudText>
                        </CardHeaderContent>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudSimpleTable Dense="true">
                            <tbody>
                                <tr>
                                    <td><strong>پکیج طلایی:</strong></td>
                                    <td>
                                        @if (_userInfo.HasPurchasedGoldenPackage)
                                        {
                                            <MudChip T="string" Color="Color.Success" Size="Size.Small" Icon="@Icons.Material.Filled.CheckCircle">
                                                خریداری شده
                                            </MudChip>
                                            <MudText Typo="Typo.caption" Color="Color.Secondary">
                                                روش: @GetPackagePurchaseMethodText(_userInfo.PackagePurchaseMethod)
                                            </MudText>
                                        }
                                        else
                                        {
                                            <MudChip T="string" Color="Color.Default" Size="Size.Small">خریداری نشده</MudChip>
                                        }
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>اعتبار دایا:</strong></td>
                                    <td>
                                        @if (_userInfo.HasReceivedDayaCredit)
                                        {
                                            <MudStack Spacing="1">
                                                <MudChip T="string" Color="Color.Success" Size="Size.Small" Icon="@Icons.Material.Filled.CheckCircle">
                                                    دریافت شده
                                                </MudChip>
                                                @if (_userInfo.DayaCreditReceivedAt != null)
                                                {
                                                    <MudText Typo="Typo.caption" Color="Color.Secondary">
                                                        تاریخ: @PersianDateTime.ConvertToPersianDate(_userInfo.DayaCreditReceivedAt.ToDateTime().ToLocalTime())
                                                    </MudText>
                                                }
                                            </MudStack>
                                        }
                                        else
                                        {
                                            <MudChip T="string" Color="Color.Default" Size="Size.Small">دریافت نشده</MudChip>
                                        }
                                    </td>
                                </tr>
                            </tbody>
                        </MudSimpleTable>
                    </MudCardContent>
                </MudCard>
            </MudItem>

            <!-- تاریخچه تغییرات عضویت -->
            <MudItem xs="12">
                <MudCard>
                    <MudCardHeader>
                        <CardHeaderContent>
                            <MudText Typo="Typo.h6">
                                <MudIcon Icon="@Icons.Material.Filled.History" Class="ml-1" />
                                تاریخچه تغییرات شبکه
                            </MudText>
                        </CardHeaderContent>
                    </MudCardHeader>
                    <MudCardContent>
                        @if (_networkHistoryLoading)
                        {
                            <MudProgressLinear Indeterminate="true" Color="Color.Primary" />
                        }
                        else if (_networkHistory.Any())
                        {
                            <MudTable T="NetworkMembershipHistoryModel" Items="_networkHistory" Dense="true" Hover="true">
                                <HeaderContent>
                                    <MudTh>عملیات</MudTh>
                                    <MudTh>تاریخ</MudTh>
                                    <MudTh>والد قبلی → جدید</MudTh>
                                    <MudTh>ساق قبلی → جدید</MudTh>
                                    <MudTh>دلیل</MudTh>
                                    <MudTh>توسط</MudTh>
                                </HeaderContent>
                                <RowTemplate>
                                    <MudTd DataLabel="عملیات">
                                        <MudChip T="string" Size="Size.Small" Color="Color.Info">@context.Action</MudChip>
                                    </MudTd>
                                    <MudTd DataLabel="تاریخ">@context.Created.ToDateTime().ToLocalTime().MiladiToJalaliWithTime()</MudTd>
                                    <MudTd DataLabel="والد">
                                        @if (context.OldParentId > 0 || context.NewParentId > 0)
                                        {
                                            <span>@context.OldParentId → @context.NewParentId</span>
                                        }
                                        else
                                        {
                                            <span>-</span>
                                        }
                                    </MudTd>
                                    <MudTd DataLabel="ساق">
                                        @{ var oldLeg = context.OldNetworkLeg == 0 ? "چپ" : "راست"; var newLeg = context.NewNetworkLeg == 0 ? "چپ" : "راست"; }
                                        @if (context.OldNetworkLeg != context.NewNetworkLeg)
                                        {
                                            <span>@oldLeg → @newLeg</span>
                                        }
                                        else
                                        {
                                            <span>-</span>
                                        }
                                    </MudTd>
                                    <MudTd DataLabel="دلیل">@(string.IsNullOrEmpty(context.Reason) ? "-" : context.Reason)</MudTd>
                                    <MudTd DataLabel="توسط">@(string.IsNullOrEmpty(context.PerformedBy) ? "-" : context.PerformedBy)</MudTd>
                                </RowTemplate>
                            </MudTable>
                        }
                        else
                        {
                            <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text">تاریخچه‌ای یافت نشد.</MudAlert>
                        }
                    </MudCardContent>
                </MudCard>
            </MudItem>

            <!-- عملیات -->
            <MudItem xs="12">
                <MudCard>
                    <MudCardHeader>
                        <CardHeaderContent>
                            <MudText Typo="Typo.h6">عملیات</MudText>
                        </CardHeaderContent>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudStack Row="true" Spacing="2">
                            <MudButton Variant="Variant.Filled" 
                                      Color="Color.Primary"
                                      StartIcon="@Icons.Material.Filled.AccountTree"
                                      OnClick="@(() => NavigationManager.NavigateTo($"/network/tree?userId={UserId}"))">
                                نمایش درخت کامل
                            </MudButton>
                            <MudButton Variant="Variant.Outlined" 
                                      Color="Color.Info"
                                      StartIcon="@Icons.Material.Filled.Money"
                                      OnClick="@(() => NavigationManager.NavigateTo($"/commission/payouts?userId={UserId}"))">
                                پرداخت‌های کاربر
                            </MudButton>
                            <MudButton Variant="Variant.Outlined" 
                                      Color="Color.Secondary"
                                      StartIcon="@Icons.Material.Filled.Refresh"
                                      OnClick="LoadUserInfo">
                                بروزرسانی
                            </MudButton>
                        </MudStack>
                    </MudCardContent>
                </MudCard>
            </MudItem>
        </MudGrid>
    }
    else
    {
        <MudAlert Severity="Severity.Error">
            کاربر یافت نشد یا خطایی رخ داده است.
        </MudAlert>
    }
</div>

@code {
    [Parameter] public long UserId { get; set; }
    [Inject] public NetworkMembershipContract.NetworkMembershipContractClient NetworkContract { get; set; }
    [Inject] public NavigationManager NavigationManager { get; set; }
    [Inject] public BackOffice.Services.IPersianDateTimeService PersianDateTime { get; set; }

    private GetUserNetworkResponse _userInfo;
    private bool _isLoading = true;
    private List<BreadcrumbItem> _breadcrumbs = new();
    private List<NetworkMembershipHistoryModel> _networkHistory = new();
    private bool _networkHistoryLoading;

    protected override async Task OnParametersSetAsync()
    {
        await LoadUserInfo();
        await LoadNetworkHistory();
    }

    private async Task LoadUserInfo()
    {
        _isLoading = true;
        try
        {
            var request = new GetUserNetworkRequest { UserId = UserId };
            _userInfo = await NetworkContract.GetUserNetworkAsync(request);

            _breadcrumbs = new List<BreadcrumbItem>
            {
                new BreadcrumbItem("شبکه", href: "/network/tree"),
                new BreadcrumbItem($"کاربر: {_userInfo.UserName}", href: null, disabled: true)
            };
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری اطلاعات: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void NavigateToUser(long? parentIdValue)
    {
        if (parentIdValue.HasValue)
            NavigationManager.NavigateTo($"/network/user-info/{parentIdValue.Value}");
    }

    private async Task LoadNetworkHistory()
    {
        _networkHistoryLoading = true;
        try
        {
            var request = new GetNetworkMembershipHistoryRequest
            {
                UserId = UserId,
                PageIndex = 0,
                PageSize = 50
            };
            var response = await NetworkContract.GetNetworkMembershipHistoryAsync(request);
            _networkHistory = response.Models?.ToList() ?? new();
        }
        catch
        {
            _networkHistory = new();
        }
        finally
        {
            _networkHistoryLoading = false;
        }
    }

    private string GetPackagePurchaseMethodText(int method)
    {
        return method switch
        {
            0 => "خریداری نشده",
            1 => "خرید با پول",
            2 => "خرید با بالانس",
            3 => "هدیه سیستم",
            _ => "نامشخص"
        };
    }
}
