using Microsoft.UI.Xaml.Controls;
using Sonex.Data.Records;
using System;

namespace Sonex.Client.Views;

public sealed partial class DataChangeDetailsView : UserControl, IView
{
    private string? _currentKey;
    private bool _hasChanges;

    public event EventHandler? StateChanged;

    public DataChangeDetailsView()
    {
        InitializeComponent();
        ClearValues();
    }

    public bool HasChanges => _hasChanges;
    public bool CanSave => CanEdit && HasChanges;
    public bool CanEdit => false;

    public void Clear()
    {
        _currentKey = null;
        ClearValues();
        MarkSaved();
    }

    public void Reload()
    {
        if (string.IsNullOrWhiteSpace(_currentKey))
        {
            Clear();
            return;
        }

        Load(_currentKey);
    }

    public void Load(string key)
    {
        _currentKey = key;
        var result = DataChangeRecord.Get(key).GetAwaiter().GetResult();

        if (result.Success && result.Item is not null)
        {
            LoadValues(result.Item);
        }
        else
        {
            ClearValues();
            IdProperty.Value = key;
        }

        MarkSaved();
    }

    public void Save()
    {
        MarkSaved();
    }

    public void MarkChanged()
    {
        _hasChanges = true;
        StateChanged?.Invoke(this, EventArgs.Empty);
    }

    public void MarkSaved()
    {
        _hasChanges = false;
        StateChanged?.Invoke(this, EventArgs.Empty);
    }

    private void LoadValues(DataChangeRecord log)
    {
        IdProperty.Value = log.Id.ToString();
        ChangedAtProperty.Value = DataChangeRecord.FormatChangedAt(log.ChangedAt);
        ActionTypeProperty.Value = log.ActionType;
        AccountNameProperty.Value = log.AccountName;
        TableNameProperty.Value = log.TableName;
        KeyNameProperty.Value = Text(log.KeyName);
        KeyValueProperty.Value = Text(log.KeyValue);
        ValueBeforeProperty.Value = Text(log.ValueBefore);
        ValueAfterProperty.Value = Text(log.ValueAfter);
    }

    private void ClearValues()
    {
        IdProperty.Value = string.Empty;
        ChangedAtProperty.Value = string.Empty;
        ActionTypeProperty.Value = string.Empty;
        AccountNameProperty.Value = string.Empty;
        TableNameProperty.Value = string.Empty;
        KeyNameProperty.Value = string.Empty;
        KeyValueProperty.Value = string.Empty;
        ValueBeforeProperty.Value = string.Empty;
        ValueAfterProperty.Value = string.Empty;
    }

    private static string Text(object? value)
    {
        return Convert.ToString(value) ?? string.Empty;
    }
}
