using CMSMicroservice.Protobuf.Protos.UserAddress;
using CMSMicroservice.Protobuf.Protos.City;
using Microsoft.AspNetCore.Components;
using MudBlazor;
using Severity = MudBlazor.Severity;

namespace FrontOffice.Main.Pages.Profile.Components;

public record CityModel(long Id, string Name);

public partial class AddAddressDialog : ComponentBase
{
    [CascadingParameter] private IMudDialogInstance MudDialog { get; set; } = default!;
    [Inject] private UserAddressContract.UserAddressContractClient UserAddressContract { get; set; } = default!;
    [Inject] private CityContract.CityContractClient CityContract { get; set; } = default!;

    private MudForm? _form;
    private bool _isSaving;
    private CreateCustomerAddressRequest _request = new();
    private object? _selectedCity;

    private async Task<IEnumerable<object>> SearchCities(string value, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(value) || value.Length < 2)
            return Enumerable.Empty<object>();

        try
        {
            var response = await CityContract.GetAllCitiesByFilterAsync(new GetAllCitiesByFilterRequest
            {
                PaginationState = new CMSMicroservice.Protobuf.Protos.City.PaginationState { PageNumber = 1, PageSize = 20 },
                Filter = new GetAllCitiesByFilterFilter { Name = value }
            });
            
            return response?.Cities?.Cast<object>() ?? Enumerable.Empty<object>();
        }
        catch
        {
            return Enumerable.Empty<object>();
        }
    }

    private async Task SaveAddress()
    {
        if (_form == null) return;

        await _form.Validate();
        if (!_form.IsValid || _selectedCity == null)
        {
            if (_selectedCity == null)
                Snackbar.Add("لطفاً شهر را انتخاب کنید.", Severity.Warning);
            return;
        }

        _request.CityId = (long)((dynamic)_selectedCity).Id;
        _isSaving = true;
        try
        {
            var response = await UserAddressContract.CreateCustomerAddressAsync(_request);
            Snackbar.Add("آدرس با موفقیت اضافه شد.", Severity.Success);
            MudDialog.Close(DialogResult.Ok(true));
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSaving = false;
            await InvokeAsync(StateHasChanged);
        }
    }


    private void Cancel() => MudDialog.Close(DialogResult.Cancel());
}