using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Shapes;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace LOLRLCG.ViewModels;

public class ChampionWrapper
{
    public Dictionary<string, Champion> Data { get; set; }
}

public class ImageInfo
{
    public string Full { get; set; }
}

public class Champion : ObservableObject
{
    public string Id { get; init; }
    private string _name;
    public string Title { get; init; }
    public List<string> Tags { get; init; }
    public ImageInfo Image { get; set; }
    private string? _uri;

    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    public string? Uri
    {
        get => _uri;
        set => SetProperty(ref _uri, value);
    }
    
    public Champion(string id, string name, string title, List<string> tags, ImageInfo image, string? uri = null)
    {
        this.Id = id;
        this.Name = name;
        this.Title = title;
        this.Tags = tags;
        this.Image = image;
        this.Uri = uri;
    }
}

public partial class MainWindowViewModel : ViewModelBase
{
    private HttpClient httpClient = new HttpClient();
    private List<string> Lanes = new List<string>(["Top", "Mid", "Bot", "Sup", "Jgl"]);
    
    private List<Champion>? _championList = new List<Champion>();
    private Champion? _selectedChampion;

    private string? _lane;
    private Bitmap? _laneImage;

    private string? _leagueClientVersion;

    public RelayCommand getRandomChampionLaneComboCommand { get; private set; }
    
    public Champion? SelectedChampion
    {
        get => _selectedChampion;
        set => SetProperty(ref _selectedChampion, value);
    }

    public string Lane
    {
        get => _lane;
        set => SetProperty(ref _lane, value);
    }
    
    public Bitmap? LaneImage
    {
        get => _laneImage;
        set => SetProperty(ref _laneImage, value);
    }

    public string? LeagueClientVersion
    {
        get => _leagueClientVersion;
        set => SetProperty(ref _leagueClientVersion, value);
    }
    
    private async Task LoadAndSetChampionImageAsync(Champion champ)
    {
        champ.Uri = $"http://ddragon.leagueoflegends.com/cdn/{LeagueClientVersion}/img/champion/{champ.Image.Full}";
        // champ.Uri = await LoadChampionImageAsync(champ);
    }
    
    private async Task<Bitmap?> LoadChampionImageAsync(Champion? champ)
    {
        if(champ == null) return null;
        var imageUrl = $"http://ddragon.leagueoflegends.com/cdn/{LeagueClientVersion}/img/champion/{champ.Image.Full}";
        try
        {
            await using var stream = await httpClient.GetStreamAsync(imageUrl);
            return new Bitmap(stream);
        }
        catch
        {
            return null;
        }
    }

    private async Task<string> getClientVersion()
    {
        try
        {
            var versionStr = await httpClient.GetStringAsync("https://ddragon.leagueoflegends.com/api/versions.json");
            var versions = JsonSerializer.Deserialize<List<string>>(versionStr);
            return versions?[0] ?? "Unavailable";
        }
        catch
        {
            return "Unavailable";
        }
    }
    
    private async Task getChampions()
    {
        if (httpClient == null) httpClient = new HttpClient();

        LeagueClientVersion = await getClientVersion();
        if (LeagueClientVersion == "Unavailable") return;

        try
        {
            var url = $"http://ddragon.leagueoflegends.com/cdn/{LeagueClientVersion}/data/de_DE/champion.json";
            var json = await httpClient.GetStringAsync(url);
            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                IgnoreReadOnlyProperties = true,
                AllowTrailingCommas = true,
                DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
            };

            var wrapper = JsonSerializer.Deserialize<ChampionWrapper>(json, options);
            
            _championList = wrapper?.Data?.Values.ToList() ?? new List<Champion>();
            
        }
        catch (Exception ex)
        {
            Console.WriteLine("Fehler beim Laden der Champion-Daten: " + ex.Message);
        }
    }
    
    private async void getRandomChampionLaneComboCommandExecute()
    {
        var champ = _championList?[Random.Shared.Next(_championList.Count)];
        if (champ != null)
        {
            await LoadAndSetChampionImageAsync(champ);
            // champ.ImageBitmap = await LoadChampionImageAsync(champ);
            SelectedChampion = champ;
        }        
        Lane = Lanes[Random.Shared.Next(Lanes.Count)];
    }

    public async Task InitAsync()
    {
        await getClientVersion();
        await getChampions();
    }
    
    public MainWindowViewModel()
    {
        getRandomChampionLaneComboCommand = new RelayCommand(getRandomChampionLaneComboCommandExecute);
        _ = InitAsync();
    }
}