using CMSMicroservice.Protobuf.Protos.User;

using FrontOffice.Main.Utilities;
using Microsoft.AspNetCore.Components;
using MudBlazor;
using Severity = MudBlazor.Severity;

namespace FrontOffice.Main.Pages.Profile;

public partial class Personal : ComponentBase
{
    [Inject] private UserContract.UserContractClient UserContract { get; set; } = default!;

    private GetUserForCustomerResponse _userProfile = new();
    private UpdateCustomerProfileRequest _updateUserRequest = new();

    private MudForm? _personalForm;
    private DateTime? _date;
    private bool _isPersonalSaving;

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

    private async Task LoadUserProfile()
    {
        try
        {
            _userProfile = await UserContract.GetUserForCustomerAsync(new());
            _updateUserRequest = new UpdateCustomerProfileRequest
            {
                FirstName = _userProfile.FirstName,
                LastName = _userProfile.LastName,
                Email = _userProfile.Email,
                NationalCode = _userProfile.NationalCode,
            };
            if (_userProfile.BirthDate != null)
                _date = _userProfile.BirthDate.ToDateTime();
        }
        catch
        {
            _userProfile = new();
        }
    }

    private async Task SavePersonalInfo()
    {
        if (_personalForm is null) return;
        await _personalForm.Validate();
        if (!_personalForm.IsValid) return;

        _isPersonalSaving = true;
        try
        {
            if (!string.IsNullOrWhiteSpace(_updateUserRequest.NationalCode))
                _updateUserRequest.NationalCode = _updateUserRequest.NationalCode.PersianToEnglish();

            if (_date != null)
                _updateUserRequest.BirthDate = _date.Value.DateTimeToTimestamp();

            await UserContract.UpdateCustomerProfileAsync(_updateUserRequest);
            Snackbar.Add("اطلاعات شخصی با موفقیت ذخیره شد.", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در ذخیره اطلاعات: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isPersonalSaving = false;
            await InvokeAsync(StateHasChanged);
        }
    }
}

