@page "/profile"
@using WebClientBase.Shared.DTOs
@using WebClientBase.Shared
@inject HttpClient Http
@inject NavigationManager Navigation
@inject IStringLocalizer<Profile> L

@* 
    EN: User profile management page (requires authentication).
    VI: Trang quản lý hồ sơ người dùng (yêu cầu xác thực).
*@

<PageTitle>@L["Auth_Profile_Title"]</PageTitle>

<div class="profile-container">
    <div class="profile-header">
        <h1 class="profile-title">@L["Auth_Profile_Title"]</h1>
        <p class="profile-subtitle">@L["Auth_Profile_Subtitle"]</p>
    </div>

    @if (isLoading)
    {
        <div class="loading-state">
            <span class="spinner"></span>
            <p>@L["Common_Loading"]</p>
        </div>
    }
    else if (userProfile != null)
    {
        <div class="profile-content">
            <!-- Personal Information Section -->
            <section class="profile-section">
                <h2 class="section-title">@L["Auth_Profile_PersonalInfo"]</h2>
                
                <EditForm Model="@userProfile" OnValidSubmit="HandleUpdateProfile" FormName="ProfileForm">
                    <DataAnnotationsValidator />
                    
                    <div class="form-group">
                        <label for="profile-name">@L["Auth_Register_DisplayName"]</label>
                        <InputText id="profile-name" 
                                  @bind-Value="userProfile.DisplayName" 
                                  class="form-input" 
                                  disabled="@(!isEditingProfile)" />
                    </div>
                    
                    <div class="form-group">
                        <label for="profile-email">@L["Common_Email"]</label>
                        <InputText id="profile-email" 
                                  @bind-Value="userProfile.Email" 
                                  class="form-input" 
                                  disabled />
                    </div>
                    
                    <div class="form-group">
                        <label>@L["Auth_Profile_MemberSince"]</label>
                        <p class="text-secondary">@userProfile.CreatedAt.ToString("MMMM dd, yyyy")</p>
                    </div>
                    
                    @if (!isEditingProfile)
                    {
                        <button type="button" class="btn-secondary" @onclick="@(() => isEditingProfile = true)">
                            @L["Auth_Profile_EditProfile"]
                        </button>
                    }
                    else
                    {
                        <div class="btn-group">
                            <button type="submit" class="btn-primary" disabled="@isSubmitting">
                                @L["Auth_Profile_SaveChanges"]
                            </button>
                            <button type="button" class="btn-secondary" @onclick="CancelEditProfile">
                                @L["Common_Cancel"]
                            </button>
                        </div>
                    }
                </EditForm>
            </section>

            <!-- Security Section -->
            <section class="profile-section">
                <h2 class="section-title">@L["Auth_Profile_Security"]</h2>
                
                <EditForm Model="@changePasswordModel" OnValidSubmit="HandleChangePassword" FormName="ChangePasswordForm">
                    <DataAnnotationsValidator />
                    
                    <div class="form-group">
                        <label for="current-password">@L["Auth_Profile_CurrentPassword"] *</label>
                        <InputText id="current-password" 
                                  @bind-Value="changePasswordModel.CurrentPassword" 
                                  type="password" 
                                  class="form-input" 
                                  placeholder="••••••••" />
                        <ValidationMessage For="() => changePasswordModel.CurrentPassword" class="validation-message" />
                    </div>
                    
                    <div class="form-group">
                        <label for="new-password">@L["Auth_Profile_NewPassword"] *</label>
                        <InputText id="new-password" 
                                  @bind-Value="changePasswordModel.NewPassword" 
                                  type="password" 
                                  class="form-input" 
                                  placeholder="••••••••" />
                        <small class="form-hint">@L["Auth_Register_PasswordHint"]</small>
                        <ValidationMessage For="() => changePasswordModel.NewPassword" class="validation-message" />
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm-new-password">@L["Auth_Profile_ConfirmPassword"] *</label>
                        <InputText id="confirm-new-password" 
                                  @bind-Value="changePasswordModel.ConfirmPassword" 
                                  type="password" 
                                  class="form-input" 
                                  placeholder="••••••••" />
                        <ValidationMessage For="() => changePasswordModel.ConfirmPassword" class="validation-message" />
                    </div>
                    
                    <button type="submit" class="btn-primary" disabled="@isSubmitting">
                        @if (isSubmitting)
                        {
                            <span class="spinner-small"></span>
                            <span>@L["Common_Loading"]</span>
                        }
                        else
                        {
                            @L["Auth_Profile_UpdatePassword"]
                        }
                    </button>
                </EditForm>
            </section>

            @if (!string.IsNullOrEmpty(message))
            {
                <div class="alert @(success ? "alert-success" : "alert-error")">
                    @message
                </div>
            }

            <div class="profile-actions">
                <button class="btn-secondary" @onclick="HandleLogout">
                    @L["Auth_Profile_Logout"]
                </button>
            </div>
        </div>
    }
</div>

@code {
    private UserProfileDto? userProfile;
    private ChangePasswordDto changePasswordModel = new();
    private bool isLoading = true;
    private bool isEditingProfile = false;
    private bool isSubmitting = false;
    private string message = "";
    private bool success = false;

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

    /// <summary>
    /// EN: Load user profile data.
    /// VI: Tải dữ liệu hồ sơ người dùng.
    /// </summary>
    private async Task LoadUserProfile()
    {
        try
        {
            var response = await Http.GetAsync("api/auth/profile");
            
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync<ApiResponse<UserProfileDto>>();
                userProfile = result?.Data;
            }
            else
            {
                // EN: Redirect to login if unauthorized
                // VI: Chuyển hướng đến đăng nhập nếu chưa xác thực
                Navigation.NavigateTo("/login");
            }
        }
        catch (Exception ex)
        {
            message = $"{L["Common_Error"]}: {ex.Message}";
            success = false;
        }
        finally
        {
            isLoading = false;
        }
    }

    /// <summary>
    /// EN: Handle profile update.
    /// VI: Xử lý cập nhật hồ sơ.
    /// </summary>
    private async Task HandleUpdateProfile()
    {
        isSubmitting = true;
        message = "";

        try
        {
            var response = await Http.PutAsJsonAsync("api/auth/profile", userProfile);
            
            if (response.IsSuccessStatusCode)
            {
                success = true;
                message = L["Auth_Profile_Success"];
                isEditingProfile = false;
            }
            else
            {
                success = false;
                message = L["Auth_Profile_Error"];
            }
        }
        catch (Exception ex)
        {
            success = false;
            message = $"{L["Common_Error"]}: {ex.Message}";
        }
        finally
        {
            isSubmitting = false;
        }
    }

    /// <summary>
    /// EN: Handle password change.
    /// VI: Xử lý đổi mật khẩu.
    /// </summary>
    private async Task HandleChangePassword()
    {
        isSubmitting = true;
        message = "";

        try
        {
            var response = await Http.PostAsJsonAsync("api/auth/change-password", changePasswordModel);
            
            if (response.IsSuccessStatusCode)
            {
                success = true;
                message = L["Auth_Profile_PasswordSuccess"];
                changePasswordModel = new(); // Clear form
            }
            else
            {
                success = false;
                message = L["Auth_Profile_Error"];
            }
        }
        catch (Exception ex)
        {
            success = false;
            message = $"{L["Common_Error"]}: {ex.Message}";
        }
        finally
        {
            isSubmitting = false;
        }
    }

    /// <summary>
    /// EN: Cancel profile editing.
    /// VI: Hủy chỉnh sửa hồ sơ.
    /// </summary>
    private async Task CancelEditProfile()
    {
        isEditingProfile = false;
        // Reload to reset changes
        await LoadUserProfile();
    }

    /// <summary>
    /// EN: Handle user logout.
    /// VI: Xử lý đăng xuất.
    /// </summary>
    private async Task HandleLogout()
    {
        try
        {
            await Http.PostAsync("api/auth/logout", null);
            Navigation.NavigateTo("/login");
        }
        catch
        {
            // EN: Even if logout fails, navigate to login
            // VI: Ngay cả khi đăng xuất thất bại, chuyển về đăng nhập
            Navigation.NavigateTo("/login");
        }
    }
}
