using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace ITNexusAgent.UI;

public partial class AdminLoginDialog : Window
{
    public string Token { get; private set; } = "";
    public string Username { get; private set; } = "";
    private readonly string _serverUrl;

    public AdminLoginDialog(string serverUrl)
    {
        InitializeComponent();
        _serverUrl = serverUrl.TrimEnd('/');
    }

    private async void Login_Click(object sender, RoutedEventArgs e)
    {
        var username = UsernameBox.Text.Trim();
        var password = PasswordBox.Password;
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return;

        LoginButton.IsEnabled = false;
        ErrorLabel.Visibility = Visibility.Collapsed;

        try
        {
            using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
            var body = JsonConvert.SerializeObject(new { username, password });
            var resp = await http.PostAsync($"{_serverUrl}/api/auth/login",
                new StringContent(body, Encoding.UTF8, "application/json"));
            var json = await resp.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeAnonymousType(json, new { token = "" });

            if (resp.IsSuccessStatusCode && !string.IsNullOrEmpty(result?.token))
            {
                Token = result.token;
                Username = username;
                DialogResult = true;
            }
            else
            {
                ErrorLabel.Text = "Ungültige Anmeldedaten";
                ErrorLabel.Visibility = Visibility.Visible;
            }
        }
        catch
        {
            ErrorLabel.Text = "Verbindung fehlgeschlagen";
            ErrorLabel.Visibility = Visibility.Visible;
        }
        finally { LoginButton.IsEnabled = true; }
    }

    private void PasswordBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key == Key.Enter) Login_Click(sender, new RoutedEventArgs());
    }

    private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false;
}
