using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using Elfisa.Core;

namespace Elfisa.Avalonia.ViewModels;

public partial class SettingsViewModel : ViewModelBase
{
    private readonly ApiClient _api = new();

    [ObservableProperty] private string _apiBaseUrl = "";
    public string[] Themes { get; } = { "Светлая", "Тёмная" };
    [ObservableProperty] private int _themeIndex;

    public ObservableCollection<BuyerLocationDto> Locations { get; } = new();
    [ObservableProperty] private BuyerLocationDto? _selectedLocation;

    public SettingsViewModel()
    {
        _api.SetToken(Session.Current.Token);
        ApiBaseUrl = SettingsStore.Current.ApiBaseUrl ?? AppConfig.DefaultApiBaseUrl;
        ThemeIndex = SettingsStore.Current.Theme == "Dark" ? 1 : 0;
        if (Session.Current.IsAuthenticated) _ = LoadLocationsAsync();
    }

    private async Task LoadLocationsAsync()
    {
        try
        {
            var locs = await _api.GetBuyerLocationsAsync();
            Locations.Clear();
            foreach (var l in locs) Locations.Add(l);
            var savedId = SettingsStore.Current.DefaultLocationId;
            SelectedLocation = Locations.FirstOrDefault(l => l.BuyerLocationId == savedId)
                               ?? Locations.FirstOrDefault(l => l.IsDefault)
                               ?? Locations.FirstOrDefault();
        }
        catch { /* локации не критичны для настроек */ }
    }
}
