using Avalonia.Controls;
using Avalonia.Controls.Converters;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Styling;
using InABox.Core;
using Microsoft.Maui.Devices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace InABox.Avalonia.Components;

public abstract class AvaloniaDataGridColumn : IAvaloniaDataGridColumn
{
    public string ColumnName { get; set; }
    public string Caption { get; set; }
    public GridLength Width { get; set; }
    public TextAlignment Alignment { get; set; }
    public virtual bool Searchable => true;

    public Action<IAvaloniaDataGridColumn, object?>? Tapped { get; set; }

    public abstract DataGridColumn CreateColumn();

    public abstract bool Filter(object? item, string filter);
}
public abstract class AvaloniaDataGridColumn<TEntity, TType> : AvaloniaDataGridColumn
{
    public Expression<Func<TEntity, TType>> Column
    {
        set
        {
            ColumnName = CoreUtils.ExpressionToString(value).Replace("x => x.", "");
        }
    }

    public TColumn CreateColumn<TColumn>() where TColumn : DataGridColumn, new()
    {
        var result = new TColumn();
        result.Header = Caption.NotWhiteSpaceOr(ColumnName);
        result.HeaderTemplate = new FuncDataTemplate<object?>((value, scope) =>
        {
            return new TextBlock
            {
                Text = value?.ToString(),
                TextAlignment = Alignment,
                Margin = Alignment switch
                {
                    TextAlignment.Center => new(0, 0, 0, 0),
                    TextAlignment.Right => new(0, 0, 12, 0),
                    TextAlignment.Left or TextAlignment.Start or _ => new(12, 0, 0, 0),
                }
            };
        });
        if(result is DataGridBoundColumn bound)
        {
            bound.Binding = new Binding(ColumnName, BindingMode.OneWay);
        }
        result.Width = new DataGridLength(Width.Value, Width.GridUnitType switch
        {
            GridUnitType.Auto => DataGridLengthUnitType.Auto,
            GridUnitType.Pixel => DataGridLengthUnitType.Pixel,
            GridUnitType.Star or _ => DataGridLengthUnitType.Star
        });
        return result;
    }

    public sealed override bool Filter(object? item, string filter)
    {
        return Filter((TEntity)item, filter);
    }
    public virtual bool Filter(TEntity item, string filter)
    {
        if (item is null) return false;
        var value = CoreUtils.GetPropertyValue(item, ColumnName);
        var sValue = value?.ToString() ?? "";
        return sValue.Contains(filter, StringComparison.CurrentCultureIgnoreCase);
    }
}
