using InABox.Clients;
using InABox.Core;
using InABox.Wpf;
using InABox.WPF;
using Syncfusion.Data;
using Syncfusion.UI.Xaml.Grid;
using Syncfusion.UI.Xaml.ScrollAxis;
using Syncfusion.UI.Xaml.TreeGrid;
using Syncfusion.UI.Xaml.TreeGrid.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Syncfusion.UI.Xaml.TreeGrid.Filtering;
using Syncfusion.UI.Xaml.TreeGrid.Cells;
using System.Windows.Controls.Primitives;
using NPOI.OpenXmlFormats.Dml;
using System.Windows.Navigation;
using NavigationMode = Syncfusion.UI.Xaml.Grid.NavigationMode;
using javax.sql.rowset;

namespace InABox.DynamicGrid;

public enum DynamicTreeGridLines
{
    Both,
    Horizontal,
    Vertical,
    None
}

public enum DynamicTreeGridExpandMode
{
    All,
    Root,
    None
}

public class DynamicGridTreeUIComponent<T, TKey> : IDynamicGridUIComponent<T>, IDynamicGridGridUIComponent
    where T : BaseObject, new()
{
    private IDynamicGridUIComponentParent<T> _parent;
    public IDynamicGridUIComponentParent<T> Parent
    {
        get => _parent;
        set
        {
            _parent = value;

            CellBackgroundConverter = new CellStyleConverter<System.Windows.Media.Brush?>(this, GetCellBackground);
            CellForegroundConverter = new CellStyleConverter<System.Windows.Media.Brush?>(this, GetCellForeground);
            CellFontSizeConverter = new CellStyleConverter<double?>(this, GetCellFontSize);
            CellFontStyleConverter = new CellStyleConverter<System.Windows.FontStyle?>(this, GetCellFontStyle);
            CellFontWeightConverter = new CellStyleConverter<System.Windows.FontWeight?>(this, GetCellFontWeight);

            if(IDColumn is not null)
            {
                Parent.AddHiddenColumn(IDColumn.Property);
            }
            if(ParentColumn is not null)
            {
                Parent.AddHiddenColumn(ParentColumn.Property);
            }
        }
    }

    private readonly TKey NullKey;

    private readonly Func<CoreRow, TKey>? IDKey;
    private readonly Func<CoreRow, TKey>? ParentKey;
    private readonly Action<T, TKey>? SetParentKey;

    private readonly Column<T>? IDColumn;
    private readonly Column<T>? ParentColumn;

    private ContextMenu _menu;
    private SfTreeGrid _tree;
    private Grid _summaryRow;
    private readonly ContextMenu ColumnsMenu;

    public event OnContextMenuOpening<TKey> OnContextMenuOpening;

    FrameworkElement IDynamicGridUIComponent.Control => _tree;

    private bool _shownumbers = false;
    public bool ShowNumbers
    {
        get => _shownumbers;
        set
        {
            _shownumbers = value;
            //_tree.Columns[1].Width = value ? 50 : 0;
        } 
    }

    private bool _showHeader = false;
    public bool ShowHeader
    {
        get => _showHeader;
        set
        {
            _showHeader = value;
            _tree.HeaderRowHeight = value ? 30 : 0;
        }
    }

    private bool _autoSizeExpander = false;
    public bool AutoSizeExpander
    {
        get => _autoSizeExpander;
        set
        {
            _autoSizeExpander = value;
            _tree.AllowAutoSizingExpanderColumn = value;
        }
    }

    private DynamicTreeGridLines _gridLines = DynamicTreeGridLines.Both;
    public DynamicTreeGridLines GridLines
    {
        get => _gridLines;
        set
        {
            _gridLines = value;
            _tree.GridLinesVisibility = value switch
            {
                DynamicTreeGridLines.Both => GridLinesVisibility.Both,
                DynamicTreeGridLines.Vertical => GridLinesVisibility.Vertical,
                DynamicTreeGridLines.Horizontal => GridLinesVisibility.Horizontal,
                _ => GridLinesVisibility.None,
            };
        }
    }

    public DynamicTreeGridExpandMode ExpandMode
    {
        get
        {
            return _tree.AutoExpandMode switch
            {
                AutoExpandMode.AllNodesExpanded => DynamicTreeGridExpandMode.All,
                AutoExpandMode.RootNodesExpanded => DynamicTreeGridExpandMode.Root,
                _ => DynamicTreeGridExpandMode.None,
            };
        }
        set
        {
            _tree.AutoExpandMode = value switch
            {
                DynamicTreeGridExpandMode.All => AutoExpandMode.AllNodesExpanded,
                DynamicTreeGridExpandMode.Root => AutoExpandMode.RootNodesExpanded,
                _ => AutoExpandMode.None
            };
        }
    }

    public void ExpandAll() => _tree.ExpandAllNodes();
    public void CollapseAll() => _tree.CollapseAllNodes();

    public bool Collapsed() => _tree.View.Nodes.Any(x => x.IsExpanded) == false;

    private double minRowHeight = 30D;
    private double maxRowHeight = 30D;

    public double MinRowHeight 
    { 
        get => minRowHeight;
        set
        {
            minRowHeight = value;
            CalculateRowHeight();
        }
    }
    public double MaxRowHeight 
    { 
        get => maxRowHeight;
        set
        {
            maxRowHeight = value;
            CalculateRowHeight();
        }
    }

    #region IDynamicGridGridUIComponent

    IList<DynamicColumnBase> IDynamicGridGridUIComponent.ColumnList => ColumnList;

    int IDynamicGridGridUIComponent.RowHeight => (int)RowHeight;

    #endregion

    private CellStyleConverter<System.Windows.Media.Brush?> CellBackgroundConverter;
    private CellStyleConverter<System.Windows.Media.Brush?> CellForegroundConverter;
    private CellStyleConverter<double?> CellFontSizeConverter;
    private CellStyleConverter<System.Windows.FontStyle?> CellFontStyleConverter;
    private CellStyleConverter<System.Windows.FontWeight?> CellFontWeightConverter;

    public DynamicGridTreeUIComponent(Func<CoreRow, TKey> idKey, Func<CoreRow, TKey> parentKey, TKey nullKey, Action<T, TKey> setParentKey): this()
    {
        IDKey = idKey;
        ParentKey = parentKey;
        NullKey = nullKey;
        SetParentKey = setParentKey;
    }

    public DynamicGridTreeUIComponent(Expression<Func<T, TKey>> idColumn, Expression<Func<T, TKey>>? parentIDColumn, TKey nullKey): this()
    {
        IDColumn = new Column<T>(CoreUtils.GetFullPropertyName(idColumn, "."));
        if(parentIDColumn is not null)
        {
            ParentColumn = new Column<T>(CoreUtils.GetFullPropertyName(parentIDColumn, "."));
        }
        NullKey = nullKey;
    }

    private DynamicGridTreeUIComponent()
    {
        ColumnsMenu = new ContextMenu();
        ColumnsMenu.Opened += ColumnsMenu_ContextMenuOpening;

        _tree = new SfTreeGrid();
        _tree.ChildPropertyName = "Children";
        //_tree.ParentPropertyName = "Parent";
        _tree.AutoGenerateColumns = false;
        ExpandMode = DynamicTreeGridExpandMode.All;
        //_tree.NodeCollapsing += (o, e) => { e.Cancel = true; };
        //_tree.HeaderRowHeight = 0D;
        _tree.HeaderRowHeight = 30;
        _tree.HeaderContextMenu = ColumnsMenu;

        _tree.SelectionChanging += _tree_SelectionChanging;
        _tree.SelectionChanged += _tree_SelectionChanged;
        _tree.AllowSelectionOnExpanderClick = false;

        _tree.AllowAutoSizingExpanderColumn = false;

        _tree.CellTapped += _tree_CellTapped;
        _tree.CellDoubleTapped += _tree_CellDoubleTapped;
        _tree.KeyUp += _tree_KeyUp;

        _tree.Loaded += _tree_Loaded;

        _tree.CellToolTipOpening += _tree_CellToolTipOpening;

        _menu = new ContextMenu();
        var additem = new MenuItem() { Header = "Add Child Folder" };
        additem.Click += (o, e) => { DoAddItem((_tree.SelectedItem as CoreTreeNode<TKey>)!.ID, true); };
        _menu.Items.Add(additem);

        _tree.ContextMenuOpening += _tree_ContextMenuOpening;
        _tree.ContextMenu = _menu;
        _tree.Background = new SolidColorBrush(Colors.DimGray);
        
        var cellStyle = new Style(typeof(TreeGridRowControl));
        cellStyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.White)));
        _tree.RowStyle = cellStyle;

        var filterstyle = new Style(typeof(TreeGridFilterControl));
        filterstyle.Setters.Add(new Setter(TreeGridFilterControl.SortOptionVisibilityProperty, Visibility.Collapsed));
        filterstyle.Setters.Add(new Setter(TreeGridFilterControl.ImmediateUpdateColumnFilterProperty, false));
        _tree.FilterPopupStyle = filterstyle;

        _tree.FilterChanged += _tree_FilterChanged;
        _tree.FilterLevel = FilterLevel.Extended;
        _tree.SelectionForeground = DynamicGridUtils.SelectionForeground;
        _tree.SelectionBackground = DynamicGridUtils.SelectionBackground;

        _tree.EditTrigger = EditTrigger.OnTap;
        _tree.CurrentCellBeginEdit += _tree_CurrentCellBeginEdit;
        _tree.CurrentCellEndEdit += _tree_CurrentCellEndEdit;
        _tree.CurrentCellDropDownSelectionChanged += _tree_CurrentCellDropDownSelectionChanged;
        _tree.PreviewKeyUp += _tree_PreviewKeyUp;
        _tree.SelectionController = new TreeGridSelectionControllerExt(_tree, this);
        
        _tree.ColumnSizer = TreeColumnSizer.None;
        _tree.RowHeight = 30D;
        _tree.SetValue(Grid.RowProperty, 0);

        _tree.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Visible);

        _tree.AllowDraggingRows = false;
        _tree.Drop += _tree_Drop;
        _tree.DragOver += _tree_DragOver;
        _tree.RowDragDropTemplate = TemplateGenerator.CreateDataTemplate(() =>
        {
            var border = new Border();
            border.Width = 100;
            border.Height = 100;
            border.BorderBrush = new SolidColorBrush(Colors.Firebrick);
            border.Background = new SolidColorBrush(Colors.Red);
            border.CornerRadius = new CornerRadius(5);
            return border;
        });

        _tree.SizeChanged += _tree_SizeChanged;
        _tree.NodeCollapsed += (sender, args) =>
        {
            ResizeColumns(_tree, _tree.Width - 2, _tree.Height - 2);
        };
        _tree.NodeExpanded += (sender, args) =>
        {
            ResizeColumns(_tree, _tree.Width - 2, _tree.Height - 2);
        };
    }

    private System.Windows.Controls.ScrollChangedEventHandler? _summaryScrollChangedHandler;

    private void _tree_Loaded(object sender, RoutedEventArgs e)
    {
        Application.Current.Dispatcher.BeginInvoke(() =>
        {
            var firstTime = _summaryRow is null;
            if (firstTime)
            {
                _summaryRow = new Grid();
                _summaryRow.Visibility = Nodes is not null && Summaries.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
            }

            var scroll = _tree.FindChild<ScrollViewer>("PART_ScrollViewer");
            if(scroll is not null)
            {
                var grid = scroll.FindVisualChildren<Grid>(recursive: false).FirstOrDefault();
                if(grid is not null)
                {
                    if (firstTime)
                    {
                        var row1 = grid.RowDefinitions[0];
                        var row2 = grid.RowDefinitions[1];
                        grid.RowDefinitions.Clear();
                        grid.RowDefinitions.Add(row1);
                        var rowDef = grid.AddRow(GridUnitType.Auto);

                        grid.RowDefinitions.Add(row2);

                        foreach(var child in grid.Children.OfType<UIElement>())
                        {
                            var row = Grid.GetRow(child);
                            if(row >= 1)
                            {
                                Grid.SetRow(child, row + 1);
                            }
                            else
                            {
                                var rowSpan = Grid.GetRowSpan(child);
                                if(row + rowSpan >= 1 && child is ScrollBar)
                                {
                                    Grid.SetRowSpan(child, rowSpan + 1);
                                }
                            }
                        }
                    }

                    var treeGridPanel = scroll.FindChild<TreeGridPanel>("PART_TreeGridPanel");

                    var summaryScroll = grid.FindChild<ScrollViewer>("PART_SummaryScroll");
                    if (summaryScroll is null)
                    {
                        summaryScroll = new ScrollViewer
                        {
                            VerticalScrollBarVisibility = ScrollBarVisibility.Hidden,
                            HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden,
                            Name = "PART_SummaryScroll"
                        };
                        summaryScroll.Content = _summaryRow;

                        if(_summaryScrollChangedHandler is not null)
                        {
                            scroll.ScrollChanged -= _summaryScrollChangedHandler;
                        }
                        _summaryScrollChangedHandler = (o, e) =>
                        {
                            summaryScroll.ScrollToHorizontalOffset(scroll.HorizontalOffset);
                        };
                        scroll.ScrollChanged += _summaryScrollChangedHandler;

                        grid.AddChild(summaryScroll, 1, 0);
                    }

                    var transform = new TranslateTransform();
                    summaryScroll.RenderTransform = transform;

                    void UpdateSize(double height)
                    {
                        var desiredHeight = treeGridPanel.RowHeights.TotalExtent;
                        if(desiredHeight < height)
                        {
                            var diff = height - desiredHeight;
                            transform.Y = -diff - 1;
                        }
                        else
                        {
                            transform.Y = 0;
                        }
                    }

                    treeGridPanel.SizeChanged += (o, e) =>
                    {
                        UpdateSize(e.NewSize.Height);
                    };
                    _tree.FilterChanged += (o, e) =>
                    {
                        UpdateSize(treeGridPanel.ActualHeight);
                    };
                    UpdateSize(treeGridPanel.ActualHeight);
                }
            }

            RebuildSummaryRow();
        });
    }

    private class TreeGridSelectionControllerExt(SfTreeGrid treeGrid, DynamicGridTreeUIComponent<T, TKey> grid) : TreeGridRowSelectionController(treeGrid)
    {
        private DynamicGridTreeUIComponent<T, TKey> Grid = grid;

        public override bool HandleKeyDown(KeyEventArgs args)
        {
            if (args.Key == Key.Escape)
            {
                Grid.CancelEdit();
                return false;
            }
            else
            {
                return base.HandleKeyDown(args);
            }
        }
    }

    #region Public Interface

    public IEnumerable<CoreRow> GetChildren(TKey id)
    {
        return Nodes.GetChildren(id).Select(x => MapRow(x.Row)).NotNull();
    }

    #endregion

    #region Input

    private CoreTreeNode<TKey>? GetNodeFromIndex(int rowIndex)
    {
        // Syncfusion has given us the row index, so it also will give us the correct row, after sorting.
        // Hence, here we use the syncfusion DataGrid.GetRecordAtRowIndex, which *should* always return a DataRowView.
        var row = _tree.GetNodeAtRowIndex(rowIndex);
        return row?.Item as CoreTreeNode<TKey>;
    }

    private CoreRow? GetRowFromIndex(int rowIndex)
    {
        return MapRow(GetNodeFromIndex(rowIndex)?.Row);
    }

    private void _tree_CellDoubleTapped(object? sender, TreeGridCellDoubleTappedEventArgs e)
    {
        _tree.Dispatcher.BeginInvoke(() =>
        {
            // This needs to happen outside the event handler, because the items source for the tree view might change during this method, and that causes an internal exception in Syncfusion. We need to finish the event before resetting the items source.
            Parent.DoubleClickCell(GetRowFromIndex(e.RowColumnIndex.RowIndex), GetColumn(e.RowColumnIndex.ColumnIndex));
        });
    }

    private void _tree_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (sender != _tree) return;

        Parent.HandleKey(e);
    }

    private void HeaderCell_LeftMouseButtonEvent(object sender, MouseButtonEventArgs e)
    {
        if (sender is not TreeGridHeaderCell header) return;

        var index = _tree.Columns.IndexOf(header.Column);
        if (GetColumn(index) is not DynamicColumnBase column)
            return;

        if(column is DynamicActionColumn dac)
        {
            Parent.ExecuteActionColumn(dac, null);
        }
    }

    private void _tree_CellTapped(object? sender, TreeGridCellTappedEventArgs e)
    {
        if (!_tree.IsEnabled)
            return;

        if (GetColumn(e.RowColumnIndex.ColumnIndex) is not DynamicColumnBase column)
            return;

        if(e.ChangedButton == MouseButton.Left)
        {
            if(column is DynamicActionColumn dac)
            {
                Parent.ExecuteActionColumn(dac, SelectedRows);
            }
        }
        else if(e.ChangedButton == MouseButton.Right)
        {
            if(column is DynamicMenuColumn dmc)
            {
                Parent.ExecuteActionColumn(dmc, null);
            }
            else
            {
                Parent.OpenColumnMenu(column);
            }
        }
    }

    #endregion

    #region Selection

    public CoreRow[] SelectedRows
    {
        get
        {
            return _tree.SelectedItems.OfType<CoreTreeNode<TKey>>()
                .Select(x => GetRow(x)).NotNull().ToArray();
        }
        set
        {
            _tree.SelectedItems.Clear();
            foreach (var row in value)
            {
                _tree.SelectedItems.Add(Nodes.Find(GetIDKey(row)));
            }
        }
    }

    private void _tree_SelectionChanged(object? sender, GridSelectionChangedEventArgs e)
    {
        if(Parent.IsReady && !Parent.IsRefreshing)
        {
            Parent.SelectItems(SelectedRows);
        }
    }

    private void _tree_SelectionChanging(object? sender, GridSelectionChangingEventArgs e)
    {
        var cancel = new CancelEventArgs();
        Parent.BeforeSelection(cancel);
        if (cancel.Cancel)
        {
            e.Cancel = true;
        }
    }

    #endregion

    #region FilterUI

    private readonly Dictionary<string, string> FilterPredicates = new();

    private void _tree_FilterChanged(object? sender, TreeGridFilterChangedEventArgs e)
    {
        if (e.FilterPredicates == null)
        {
            if (FilterPredicates.ContainsKey(e.Column.MappingName))
                FilterPredicates.Remove(e.Column.MappingName);
        }
        else
        {
            FilterPredicates[e.Column.MappingName] = Serialization.Serialize(e.FilterPredicates, true);
        }
        
        Parent.UIFilterChanged(this);

        UpdateRecordCount();
        CalculateSummaries();
    }

    public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
    {
        if (value.IsNullOrWhiteSpace())
            return;
        var col = _tree.Columns.FirstOrDefault((x => string.Equals(x.MappingName?.ToUpper(),column?.Replace(".", "_").ToUpper())));
        if (col != null)
        {
            col.FilterPredicates.Add(new FilterPredicate { FilterType = filtertype, FilterValue = value });
        }
    }

    public List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
    {
        var list = new List<Tuple<string, Func<CoreRow, bool>>>();
        foreach (var column in _tree.Columns)
        {
            var colIndex = _tree.Columns.IndexOf(column);
            var col = ColumnList[colIndex];
            var filter = Parent.GetColumnFilter(col);

            if (col is DynamicGridColumn gridColumn)
            {
                var rowPredicate = DynamicGridGridUIComponentExtension.ConvertColumnPredicates(gridColumn, column.FilterPredicates);
                if(filter is not null)
                {
                    var oldPred = rowPredicate;
                    if(oldPred is not null)
                    {
                        rowPredicate = row => oldPred(row) && filter.FilterRow(row);
                    }
                    else
                    {
                        rowPredicate = filter.FilterRow;
                    }
                }
                if(rowPredicate is not null)
                {
                    list.Add(new(gridColumn.ColumnName, rowPredicate));
                }
            }
            else if(col is DynamicActionColumn dac)
            {
                if(filter is not null)
                {
                    list.Add(new(column.MappingName, filter.FilterRow));
                }
            }
        }
        return list;
    }

    public void SetFilter(Func<CoreRow, bool>? predicate)
    {
        if(predicate is not null)
        {
            _tree.View.Filter = o =>
            {
                if(GetRow(o as CoreTreeNode<TKey>) is CoreRow row)
                {
                    return predicate(row);
                }
                else
                {
                    return false;
                }
            };
        }
        else
        {
            _tree.View.Filter = null;
        }
        _tree.View.RefreshFilter();
        if(_tree.View.Nodes.Count == 0)
        {
            _tree.View.Refresh();
        }
    }

    #endregion

    private void ColumnsMenu_ContextMenuOpening(object sender, RoutedEventArgs e)
    {
        if (sender is not ContextMenu menu) return;
        menu.Items.Clear();

        Parent.LoadColumnsMenu(menu);
    }

    public bool OptionsChanged()
    {
        ColumnsMenu.Visibility = Parent.Options.SelectColumns ? Visibility.Visible : Visibility.Hidden;

        var allowEditing = Parent.IsDirectEditMode();
        var reloadColumns = false;

        if (_tree.AllowEditing != allowEditing)
        {
            _tree.NavigationMode = allowEditing ? NavigationMode.Cell : NavigationMode.Row;
            _tree.AllowEditing = allowEditing;
            reloadColumns = true;
        }

        if (Parent.Options.DragSource)
        {
            if (!_tree.AllowDraggingRows)
            {
                _tree.AllowDraggingRows = true;
                _tree.RowDragDropController.DragStart += RowDragDropController_DragStart;
            }
        }
        else
        {
            if (_tree.AllowDraggingRows)
            {
                _tree.AllowDraggingRows = false;
                _tree.RowDragDropController.DragStart -= RowDragDropController_DragStart;
            }
        }
        
        _tree.AllowDrop = Parent.Options.DragTarget;
        _tree.SelectionMode = Parent.Options.MultiSelect ? GridSelectionMode.Extended : GridSelectionMode.Single;

        return reloadColumns;
    }

    private void _tree_CellToolTipOpening(object? sender, TreeGridCellToolTipOpeningEventArgs e)
    {
        if (GetColumn(e.RowColumnIndex.ColumnIndex) is not DynamicActionColumn col)
            return;
        var toolTip = col.ToolTip;
        if (toolTip is null)
            return;

        var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);

        e.ToolTip.Template = TemplateGenerator.CreateControlTemplate(
            typeof(ToolTip),
            () => toolTip.Invoke(col, row)
        );
    }

    #region Styles

    private class CellStyleConverter<TValue> : IValueConverter
    {

        private readonly DynamicGridTreeUIComponent<T, TKey> _component;
        
        private readonly Func<CoreRow, DynamicColumnBase, TValue> _converter;
        
        public CellStyleConverter(DynamicGridTreeUIComponent<T, TKey> component, Func<CoreRow, DynamicColumnBase, TValue> converter)
        {
            _component = component ?? throw new ArgumentNullException(nameof(component));
            _converter = converter ?? throw new ArgumentNullException(nameof(converter));
        }

        private CoreRow? GetRow(object item)
        {
            try
            {
                if (item is CoreTreeNode<TKey> row)
                {
                    return _component.GetRow(row);
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var row = GetRow(value);
            if (row == null)
                return DependencyProperty.UnsetValue;

            var param = parameter as DynamicGridCellStyleParameters;
            if (param == null)
                return DependencyProperty.UnsetValue;
            
            //var column = parameter as DynamicColumnBase;
            //if (column is null)
            //    return DependencyProperty.UnsetValue;
            
            return _converter.Invoke(row,param.Column) ?? param.DefaultValue;
        }
        
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }

    protected virtual Brush? GetCellBackground(CoreRow row, DynamicColumnBase column) => null;
    protected virtual Brush? GetCellForeground(CoreRow row, DynamicColumnBase column) => null;
    protected virtual double? GetCellFontSize(CoreRow row, DynamicColumnBase column) => null;
    protected virtual FontStyle? GetCellFontStyle(CoreRow row, DynamicColumnBase column) => null;
    protected virtual FontWeight? GetCellFontWeight(CoreRow row, DynamicColumnBase column) => null;

    protected virtual Brush? GetCellSelectionForegroundBrush() => DynamicGridUtils.SelectionForeground;
    protected virtual Brush? GetCellSelectionBackgroundBrush() => DynamicGridUtils.SelectionBackground;

    protected virtual Style GetHeaderCellStyle(DynamicColumnBase column)
    {
        var headStyle = new Style(typeof(TreeGridHeaderCell));

        headStyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
        headStyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
        headStyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));

        if(column is DynamicActionColumn actionColumn)
        {
            headStyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0)));
            headStyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
            if(column is DynamicImageColumn imgCol)
            {
                if (imgCol.HeaderText.IsNullOrWhiteSpace())
                {
                    var image = imgCol.Image?.Invoke(null);
                    if (image != null)
                    {
                        // var template = new ControlTemplate(typeof(TreeGridHeaderCell));
                        // var border = new FrameworkElementFactory(typeof(Border));
                        // border.SetValue(Border.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro));
                        // border.SetValue(Border.PaddingProperty, new Thickness(4));
                        // border.Name = "PART_HeaderCellBorder";

                        // var img = new FrameworkElementFactory(typeof(Image));
                        // img.SetValue(Image.SourceProperty, image);
                        // border.AppendChild(img);
                        // template.VisualTree = border;
                        // headStyle.Setters.Add(new Setter(Control.TemplateProperty, template));

                        headStyle.AddSetter(GridHeaderCellControl.PaddingProperty, new Thickness(4.0));
                        headStyle.AddSetter(GridHeaderCellControl.ContentTemplateProperty,
                            TemplateGenerator.CreateDataTemplate(() =>
                            {
                                return new Image { Source = image };
                            }));
                    }
                }
            }
            if (actionColumn.VerticalHeader && !actionColumn.HeaderText.IsNullOrWhiteSpace())
            {
                headStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Left));
                headStyle.Setters.Add(new Setter(Control.TemplateProperty,
                    Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
            }
        }
        return headStyle;
    }

    protected virtual Style GetSummaryCellStyle(DynamicColumnBase column)
    {
        var style = new Style(typeof(SummaryCellControl));

        style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
        style.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));

        if(column is DynamicGridColumn gridColumn)
        {
            style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty,
                column != null ? gridColumn.HorizontalAlignment(typeof(double)) : HorizontalAlignment.Right));
        }
        else if(column is DynamicTextColumn textColumn)
        {
            style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, textColumn.Alignment.HorizontalAlignment(typeof(string))));
        }
        else
        {
            style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Right));
        }
        style.Setters.Add(new Setter(Control.VerticalContentAlignmentProperty, VerticalAlignment.Center));

        style.Setters.Add(new Setter(Control.BorderBrushProperty, new SolidColorBrush(Colors.Gray)));
        style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0, 0.75, 0.75, 0.0)));
        style.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
        style.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.DemiBold));

        style.Setters.Add(new Setter(Control.PaddingProperty, new Thickness(4)));

        return style;
    }

    #endregion

    #region Sizing

    public double RowHeight
    {
        get => _tree.RowHeight;
        set => _tree.RowHeight = value;
    }
    public double HeaderRowHeight
    {
        get => _tree.HeaderRowHeight;
        set => _tree.HeaderRowHeight = value;
    }

    private void _tree_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        CalculateRowHeight();
        if (Parent.IsReady && !Parent.IsRefreshing)
            ResizeColumns(_tree, e.NewSize.Width - 2, e.NewSize.Height - 2);
    }

    int IDynamicGridUIComponent.DesiredWidth()
    {
        return this.DesiredWidth();
    }

    #endregion

    #region Context Menu

    private void _tree_ContextMenuOpening(object sender, ContextMenuEventArgs e)
    {
        _menu.Items.Clear();
        if (OnContextMenuOpening is not null)
        {
            OnContextMenuOpening.Invoke((_tree.SelectedItem as CoreTreeNode<TKey>)!, _menu);
            if(_menu.Items.Count == 0)
            {
                e.Handled = true;
            }
        }
        else
        {
            if (Parent.Options.AddRows)
            {
                _menu.AddItem("Add Item", null, (_tree.SelectedItem as CoreTreeNode<TKey>)!.ID, (id) => DoAddItem(id, true));
            }
        }
    }

    #endregion

    #region CRUD

    protected T DoCreateItem(TKey parent)
    {
        var result = Parent.CreateItem();
        SetParent(result, parent);
        return result;
    }
    
    protected void DoAddItem(TKey id, bool edit)
    {
        try
        {
            var item = DoCreateItem(id);
            if (edit)
            {
                if (Parent.EditItems(new[] { item }))
                {
                    Parent.DoChanged();
                    Parent.Refresh(false, true);
                }
            }
            else
            {
                Parent.SaveItem(item);
                Parent.DoChanged();
                Parent.Refresh(false, true);
            }
        }
        catch (Exception e)
        {
            MessageWindow.ShowError("An error occurred while adding an item", e);
        }
    }

    #endregion

    #region Rows

    private TKey GetIDKey(CoreRow row)
    {
        if(IDColumn is not null)
        {
            return row.Get<TKey>(IDColumn.Property);
        }
        else if(IDKey is not null)
        {
            return IDKey(row);
        }
        else
        {
            return NullKey;
        }
    }
    private TKey GetParentKey(CoreRow row)
    {
        if(ParentColumn is not null)
        {
            return row.Get<TKey>(ParentColumn.Property);
        }
        else if(ParentKey is not null)
        {
            return ParentKey(row);
        }
        else
        {
            return NullKey;
        }
    }

    private void SetParent(T obj, TKey key)
    {
        if(ParentColumn is not null)
        {
            ParentColumn.PropertyDefinition.Setter()(obj, key);
        }
        else if(SetParentKey is not null)
        {
            SetParentKey(obj, key);
        }
    }

    private CoreRow? GetRow(CoreTreeNode<TKey>? node)
    {
        return MapRow(node?.Row);
    }

    /// <summary>
    /// Map a row of <see cref="_innerTable"/> to a Data row.
    /// </summary>
    private CoreRow? MapRow(CoreRow? row)
    {
        if (row is null) return null;

        return _rowMap.GetValueOrDefault(row);
    }

    private CoreTreeNode<TKey>? GetNode(CoreRow row)
    {
        foreach(var (innerRow, dataRow) in _rowMap)
        {
            if(row == dataRow)
            {
                return Nodes.Find(innerRow);
            }
        }
        return null;
    }

    public CoreRow[] GetVisibleRows()
    {
        return _tree.View?.Nodes.Select(x => GetRow(x.Item as CoreTreeNode<TKey>)).NotNull().ToArray() ?? new CoreRow[] { };
    }

    public void ExpandRow(CoreRow row)
    {
        var node = _tree.View.Nodes.GetNode(Nodes.Find(GetIDKey(row)));
        if(node is not null)
        {
            _tree.ExpandNode(node);
        }
    }

    #endregion

    #region Columns

    private class StackedHeaderRenderer : TreeGridStackedHeaderCellRenderer
    {
        private Style Style;

        public StackedHeaderRenderer()
        {
            var headstyle = new Style(typeof(TreeGridStackedHeaderCell));
            headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
            headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
            headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
            headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0, 0.0, 0, 0)));
            headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));

            Style = headstyle;
        }

        public override void OnInitializeEditElement(TreeDataColumnBase dataColumn, TreeGridStackedHeaderCell uiElement, object dataContext)
        {
            uiElement.Style = Style;
            base.OnInitializeEditElement(dataColumn, uiElement, dataContext);
        }
    }

    private readonly List<DynamicColumnBase> ColumnList = new();
    private List<DynamicActionColumn> ActionColumns = new();
    private List<Summary> Summaries = new();

    private DynamicColumnBase? GetColumn(int index) =>
        index >= 0 && index < ColumnList.Count ? ColumnList[index] : null;

    #region Column Filtering

    private void ApplyFilterStyle(TreeGridColumn column, bool filtering, bool isactioncolumn)
    {
        var filterstyle = new Style();
        if (filtering)
        {
            filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, DynamicGridUtils.FilterBackground));
            filterstyle.Setters.Add(new Setter(Control.ForegroundProperty, DynamicGridUtils.FilterForeground));
            filterstyle.Setters.Add(new Setter(GridCell.SelectionForegroundBrushProperty, DynamicGridUtils.FilterForeground));
            column.ImmediateUpdateColumnFilter = true;
            column.ColumnFilter = ColumnFilter.DisplayText;
            column.AllowBlankFilters = true;
            column.AllowSorting = isactioncolumn
                ? false
                : Parent.CanSort();
        }
        else
        {
            filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
            filterstyle.Setters.Add(new Setter(Control.ForegroundProperty, DynamicGridUtils.FilterForeground));
            filterstyle.Setters.Add(new Setter(GridCell.SelectionForegroundBrushProperty, DynamicGridUtils.FilterForeground));
            filterstyle.Setters.Add(new Setter(UIElement.IsEnabledProperty, false));
            column.ColumnFilter = ColumnFilter.Value;
            column.AllowSorting = false;
        }
    }

    private void Filter_FilterChanged(IDynamicGridColumnFilter filter)
    {
        AddRows(Parent.Data.Rows, true);
        Parent.UIFilterChanged(this);
    }

    private bool FilterRow(CoreRow row)
    {
        foreach(var column in ColumnList)
        {
            if(Parent.GetColumnFilter(column) is IDynamicGridColumnFilter filter && !filter.FilterRow(row))
            {
                return false;
            }
        }
        return true;
    }
    private IEnumerable<CoreRow> FilterRows(IEnumerable<CoreRow> rows)
    {
        var rowList = rows.Select(x => new
        {
            Row = x,
            ID = GetIDKey(x),
            Parent = GetParentKey(x)
        }).ToArray();

        var nullKey = new object();

        var allRows = rowList.ToDictionary(x => x.ID ?? nullKey);
        var lastAdded = rowList.Where(x => FilterRow(x.Row)).ToHashSet();
        var allFilteredRows = lastAdded.ToHashSet();
        var allFilteredRows1 = lastAdded.ToHashSet();

        bool updated = true;
        while (updated)
        {
            updated = false;

            var currentSet = lastAdded.NewEmpty().ToHashSet();
            foreach(var row in lastAdded)
            {
                if(allRows.TryGetValue(row.Parent ?? nullKey, out var parent))
                {
                    updated = allFilteredRows.Add(parent) || updated;
                    currentSet.Add(parent);
                }
            }
            foreach(var row in rowList)
            {
                if(allRows.TryGetValue(row.Parent ?? nullKey, out var parent) && allFilteredRows1.Contains(parent))
                {
                    updated = allFilteredRows1.Add(row) || updated;
                }
            }

            lastAdded = currentSet;
        }

        return rowList.Where(x => allFilteredRows.Contains(x) || allFilteredRows1.Contains(x)).Select(x => x.Row);
    }

    private void SetFilterUIButton(TreeGridColumn gridColumn, DynamicColumnBase column)
    {
        if (!Parent.Options.FilterRows || !Parent.CanFilter()) return;

        if (Parent.GetColumnFilter(column) is not IDynamicGridColumnFilter filter) return;

        var vertical = column is DynamicActionColumn ac && ac.VerticalHeader && !ac.HeaderText.IsNullOrWhiteSpace();

        var horizontalAlignment = gridColumn.HorizontalHeaderContentAlignment;
        gridColumn.HorizontalHeaderContentAlignment = HorizontalAlignment.Stretch;
        gridColumn.HeaderTemplate = TemplateGenerator.CreateDataTemplate(() =>
        {
            var grid = new Grid();
            grid.AddColumn(GridUnitType.Star);
            var filterCol = grid.AddColumn(GridUnitType.Auto);

            var content = new ContentControl();
            content.HorizontalAlignment = horizontalAlignment;
            content.VerticalAlignment = VerticalAlignment.Center;
            content.SetBinding(ContentControl.ContentProperty, new Binding());
            grid.AddChild(content, 0, 0);

            var button = new DynamicGridColumnFilterUIButton(filter);
            grid.AddChild(button, 0, 1);

            if(vertical)
            {
                button.LayoutTransform = new RotateTransform(90);
                content.HorizontalAlignment = HorizontalAlignment.Stretch;
            }

            return grid;
        });
    }

    #endregion

    public class TemplateColumnSelector(DynamicGridTreeUIComponent<T, TKey> parent, Func<CoreRow, FrameworkElement?> dataTemplate) : DataTemplateSelector
    {
        public Func<CoreRow, FrameworkElement?> DataTemplate { get; init; } = dataTemplate;

        public DynamicGridTreeUIComponent<T, TKey> Parent { get; init; } = parent;

        public override DataTemplate? SelectTemplate(object item, DependencyObject container)
        {
            if (item is not CoreTreeNode<TKey> node) return null;

            var row = Parent.MapRow(node.Row);

            if (row is null) return null;

            return TemplateGenerator.CreateDataTemplate(() =>
            {
                return DataTemplate(row);
            });
        }
    }

    private void LoadActionColumn(DynamicActionColumn column)
    {
        var i = ActionColumns.Count;
        var sColName = $"[_ActionColumn{i}]";
        ActionColumns.Add(column);

        var summary = column.Summary();
        if(summary is not null)
        {
            Summaries.Add(new(column, summary, null, null));
        }

        if (column is DynamicImageColumn imgcol)
        {
            var newcol = new TreeGridTemplateColumn();

            newcol.CellTemplateSelector = new TemplateColumnSelector(this, row =>
            {
                var image = new Image
                {
                    Width = _tree.RowHeight - 8,
                    Height = _tree.RowHeight - 8,
                };
                image.SetBinding(Image.SourceProperty, new Binding(sColName));
                return image;
            });

            newcol.AllowEditing = false;
            newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
            newcol.Width = column.Width == 0 ? _tree.RowHeight : column.Width;
            newcol.Padding = new Thickness(4);
            newcol.ColumnSizer = TreeColumnSizer.None;
            newcol.HeaderText = column.HeaderText;
            newcol.MappingName = sColName;

            ApplyFilterStyle(newcol, false, true);
            SetFilterUIButton(newcol, column);

            newcol.ShowToolTip = column.ToolTip != null;
            newcol.ShowHeaderToolTip = column.ToolTip != null;

            var headstyle = GetHeaderCellStyle(column);
            headstyle.Setters.Add(new EventSetter(Control.MouseLeftButtonUpEvent, new MouseButtonEventHandler(HeaderCell_LeftMouseButtonEvent)));
            newcol.HeaderStyle = headstyle;

            _tree.Columns.Add(newcol);
            ColumnList.Add(column);
        }
        else if (column is DynamicTextColumn txtCol)
        {
            var newcol = new TreeGridTextColumn();
            newcol.TextWrapping = TextWrapping.NoWrap;

            newcol.TextAlignment = txtCol.Alignment.TextAlignment(typeof(string));

            newcol.AllowEditing = false;
            newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
            newcol.MappingName = sColName;
            newcol.Width = column.Width;
            newcol.ColumnSizer = TreeColumnSizer.None;
            newcol.HeaderText = column.HeaderText;
            newcol.AllowSorting = false;
            newcol.ShowHeaderToolTip = column.ToolTip != null;
            
            ApplyFilterStyle(newcol, false, true);
            SetFilterUIButton(newcol, column);

            var headstyle = GetHeaderCellStyle(column);
            headstyle.Setters.Add(new EventSetter(Control.MouseLeftButtonUpEvent, new MouseButtonEventHandler(HeaderCell_LeftMouseButtonEvent)));
            newcol.HeaderStyle = headstyle;

            _tree.Columns.Add(newcol);
            ColumnList.Add(column);
        }
        else if (column is DynamicTemplateColumn tmplCol)
        {
            var newcol = new TreeGridTemplateColumn();
            newcol.CellTemplateSelector = new TemplateColumnSelector(this, tmplCol.Template);
            newcol.AllowEditing = false;
            newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
            
            newcol.Width = tmplCol.Width;
            newcol.ColumnSizer = TreeColumnSizer.None;
            newcol.HeaderText = column.HeaderText;
            newcol.AllowSorting = false;
            newcol.ShowToolTip = false;
            newcol.ShowHeaderToolTip = false;
            newcol.MappingName = sColName;
            
            ApplyFilterStyle(newcol, false, true);
            SetFilterUIButton(newcol, column);

            var headstyle = GetHeaderCellStyle(column);
            headstyle.Setters.Add(new EventSetter(Control.MouseLeftButtonUpEvent, new MouseButtonEventHandler(HeaderCell_LeftMouseButtonEvent)));
            newcol.HeaderStyle = headstyle;

            _tree.Columns.Add(newcol);
            ColumnList.Add(column);
        }
    }

    private void LoadDataColumn(DynamicGridColumn column)
    {
        column.Editor = Parent.CustomiseEditor(column, column.Editor);
        if(this.CreateEditorColumn<T>(column, out var newcol))
        {
            if(newcol is IDynamicGridEditorColumn<T> typed)
            {
                typed.GetEntity = () => _editingObject?.Object;
                typed.EntityChanged += DoEntityChanged;
            }

            var newColumn = newcol.CreateTreeGridColumn();

            var summary = newcol.Summary();
            if(summary is not null)
            {
                Summaries.Add(new(column, summary, null, null));
            }

            ApplyFilterStyle(newColumn, newcol.Filtered, false);
            
            newColumn.HeaderStyle = GetHeaderCellStyle(column);
            SetFilterUIButton(newColumn, column);

            var cellstyle = new Style();
            if (Parent.IsDirectEditMode())
            {
                if (column.Editor is null || !newcol.Editable || !column.Editor.Editable.IsDirectEditable())
                {
                    cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
                        new SolidColorBrush(Colors.WhiteSmoke)));
                    newColumn.AllowEditing = false;
                }
                else
                {
                    cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
                        new SolidColorBrush(Colors.LightYellow)));
                    newColumn.AllowEditing = true;
                }

                cellstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
                if(ColumnList.Count == 0)
                {
                    _tree.ExpanderCellStyle = cellstyle;
                }
            }
            else
            {
                cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
                    new Binding()
                    {
                        Converter = CellBackgroundConverter,
                        ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
                    }));
                cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
                    new Binding()
                    {
                        Converter = CellForegroundConverter, 
                        ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
                    }));
                cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
                    new Binding()
                    {
                        Converter = CellFontSizeConverter, 
                        ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
                    }));
                cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
                    new Binding()
                    {
                        Converter = CellFontStyleConverter, 
                        ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
                    }));
                cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
                    new Binding()
                    {
                        Converter = CellFontWeightConverter, 
                        ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
                    }));
                newColumn.CellStyle = cellstyle;
                if(ColumnList.Count == 0)
                {
                    _tree.ExpanderCellStyle = cellstyle;
                }
            }
            
            _tree.Columns.Add(newColumn);
            ColumnList.Add(column);
            foreach (var extra in newcol.ExtraColumns)
                Parent.AddHiddenColumn(extra);
        }
    }

    private void LoadStackedHeaders(DynamicGridColumnGroupings groupings)
    {
        _tree.StackedHeaderRows.Clear();
        foreach(var grouping in groupings)
        {
            var row = new StackedHeaderRow();
            var i = 0;
            foreach(var group in grouping.Groups)
            {
                var start = Math.Max(i, ColumnList.IndexOf(group.StartColumn));
                var end = Math.Max(start, ColumnList.IndexOf(group.EndColumn));

                if(end < start)
                {
                    i = end + 1;
                    continue;
                }

                var cols = Enumerable.Range(start, end - start + 1).Select(i => _tree.Columns[i]).ToArray();

                var stackedColumn = new StackedColumn
                {
                    HeaderText = group.Header,
                    ChildColumns = string.Join(',', cols.Select(x => x.MappingName))
                };

                row.StackedColumns.Add(stackedColumn);

                i = end + 1;
            }

            _tree.StackedHeaderRows.Add(row);
        }
        if(groupings.Count > 0)
        {
            _tree.CellRenderers.Remove("StackedHeader");
            _tree.CellRenderers.Add("StackedHeader", new StackedHeaderRenderer());
        }
    }

    public void RefreshColumns(IEnumerable<DynamicColumnBase> columns, DynamicGridColumnGroupings groupings)
    {
        _tree.ItemsSource = null;
        _tree.Columns.Suspend();

        ColumnList.Clear();
        _tree.Columns.Clear();
        Summaries.Clear();

        ActionColumns.Clear();

        foreach(var column in columns)
        {
            if(Parent.GetColumnFilter(column) is IDynamicGridColumnFilter filter)
            {
                filter.FilterChanged += Filter_FilterChanged;
            }
            if(column is DynamicActionColumn ac)
            {
                LoadActionColumn(ac);
            }
            else if(column is DynamicGridColumn gc)
            {
                LoadDataColumn(gc);
            }
        }
        
        LoadStackedHeaders(groupings);

        _tree.Columns.Resume();
        _tree.RefreshColumns();

        foreach (var key in FilterPredicates.Keys.ToArray())
            if (_tree.Columns.Any(x => string.Equals(x.MappingName, key)))
            {
                var predicates = Serialization.Deserialize<List<FilterPredicate>>(FilterPredicates[key]);
                foreach (var predicate in predicates)
                {
                    _tree.Columns[key].FilterPredicates.Add(predicate);
                }
            }
            else
            {
                FilterPredicates.Remove(key);
            }

        ResizeColumns(_tree, _tree.ActualWidth - 2, _tree.ActualHeight - 2);
    }

    // public void GetExpandedTreeDepth(TreeNode node, ref int depth)
    // {
    //     if (node == null || node.ChildNodes == null || node.ChildNodes.Count == 0)
    //         return;
    //     
    //     depth++;
    //     if (!node.IsExpanded)
    //         return;
    //     
    //     int maxChildDepth = 0;
    //     foreach (var child in node.ChildNodes)
    //     {
    //         int childdepth = 0;
    //         GetExpandedTreeDepth(child, ref childdepth);
    //         maxChildDepth = Math.Max(maxChildDepth, childdepth);
    //     }
    //     
    //     depth += maxChildDepth;
    //
    // }
    //
    // private double ExpanderWidth(double columnwidth)
    // {
    //     var depth = 0;
    //     var children = _tree.View.Nodes.Where(x => x.ParentNode == null && x.HasChildNodes);
    //     foreach (var child in children)
    //     {
    //         var childdepth = 0;
    //         GetExpandedTreeDepth(child, ref childdepth);
    //         depth = Math.Max(depth, childdepth);
    //     }
    //     return depth * columnwidth;
    // }

    private void ResizeColumns(SfTreeGrid grid, double width, double height)
    {
        if (Parent.Data == null || width <= 0)
            return;

        grid.Dispatcher.BeginInvoke(() =>
        {
            var expander = 0; //ExpanderWidth(18.0);
            var sizes = this.CalculateColumnSizes(width, false);
            foreach (var (index, size) in sizes)
            {
                var colSize = Math.Max(0.0F, size);
                _tree.Columns[index].Width = colSize.IsEffectivelyEqual(0.0) ? double.NaN : colSize;
                _tree.Columns[index].ColumnSizer = colSize.IsEffectivelyEqual(0.0) ? TreeColumnSizer.Star : TreeColumnSizer.None;
            }
            _tree.TreeGridColumnSizer.Refresh();
            
            RebuildSummaryRow();
        });
    }

    #endregion

    #region Summary

    private class Summary(DynamicColumnBase column, IDynamicGridSummary summary, SummaryCellControl? control, object? data)
    {
        public DynamicColumnBase Column { get; set; } = column;

        public IDynamicGridSummary SummaryDefinition { get; set; } = summary;

        public SummaryCellControl? Control { get; set; } = control;

        public object? Data { get; set; } = data;
    }

    protected class SummaryCellControl : ContentControl
    {
        public SummaryCellControl()
        {
            var template = new ControlTemplate(typeof(ContentControl));

            var factory = new FrameworkElementFactory(typeof(Border));
            factory.Bind<ContentControl, Brush>(Border.BorderBrushProperty, x => x.BorderBrush);
            factory.Bind<ContentControl, Thickness>(Border.BorderThicknessProperty, x => x.BorderThickness);
            factory.Bind<ContentControl, Brush>(Border.BackgroundProperty, x => x.Background);
            factory.Bind<ContentControl, Thickness>(Border.PaddingProperty, x => x.Padding);

            var content = new FrameworkElementFactory(typeof(ContentPresenter));
            content.Bind<ContentControl, HorizontalAlignment>(ContentPresenter.HorizontalAlignmentProperty, x => x.HorizontalContentAlignment);
            content.Bind<ContentControl, VerticalAlignment>(ContentPresenter.VerticalAlignmentProperty, x => x.VerticalContentAlignment);
            factory.AppendChild(content);
            template.VisualTree = factory;

            Template = template;
        }
    }

    private void RebuildSummaryRow()
    {
        if (_summaryRow is null) return;

        _summaryRow.RowDefinitions.Clear();
        _summaryRow.ColumnDefinitions.Clear();
        _summaryRow.Children.Clear();

        var row = _summaryRow.AddRow(GridUnitType.Auto);
        row.MinHeight = _tree.RowHeight;

        foreach(var (i, column) in _tree.Columns.WithIndex())
        {
            _summaryRow.AddColumn(column.ActualWidth);

            var cell = new SummaryCellControl();
            if(GetColumn(i) is DynamicColumnBase col)
            {
                cell.Style = GetSummaryCellStyle(col);

                var summary = Summaries.FirstOrDefault(x => x.Column == col);
                if(summary is not null)
                {
                    cell.Content = summary.Data;
                    summary.Control = cell;
                }
            }
            _summaryRow.AddChild(cell, 0, _summaryRow.ColumnDefinitions.Count - 1);
        }
    }

    private void CalculateSummaries()
    {
        foreach(var column in ColumnList)
        {
            CalculateSummary(column);
        }
    }

    private object? CalculateSummaryData(IDynamicGridSummary summary, DynamicColumnBase column)
    {
        var nodes = _tree.View is not null
            ? _tree.View.Nodes.Select(x => x.Item as CoreTreeNode<TKey>).NotNull()
            : Nodes.Nodes;
        if(summary is DynamicGridCountSummary count)
        {
            return string.Format("{0:N0}", nodes.Count());
        }
        else if(summary is DynamicGridSumSummary sum)
        {
            if(column is DynamicGridColumn gridColumn)
            {
                var data = nodes.Select(x => MapRow(x.Row)).NotNull()
                    .Select(x => x[gridColumn.ColumnName]);

                object? result;
                if(sum.AggregateType == typeof(double))
                {
                    result = data.Sum(x => x is double d ? d : 0);
                }
                else if(sum.AggregateType == typeof(int))
                {
                    result = data.Sum(x => x is int i ? i : 0);
                }
                else if(sum.AggregateType == typeof(TimeSpan))
                {
                    result = data.Aggregate(TimeSpan.Zero, (cur, x) => x is TimeSpan ts ? cur + ts : cur);
                }
                else
                {
                    result = null;
                }
                if(result is not null)
                {
                    return string.Format($"{{0:{sum.Format}}}", result);
                }
            }
        }
        else if(summary is DynamicGridCustomSummary custom)
        {
            var data = nodes.Select(x => MapRow(x.Row)).NotNull();
            var result = custom.Aggregate(data);
            if(result is not null)
            {
                return string.Format($"{{0:{custom.Format}}}", result);
            }
        }
        else if(summary is DynamicGridTemplateSummary template)
        {
            return template.Template();
        }
        return null;
    }

    private void CalculateSummary(DynamicColumnBase column)
    {
        var (idx, summary) = Summaries.WithIndex().FirstOrDefault(x => x.Value.Column == column);
        if(summary is null)
        {
            return;
        }
        var colIdx = ColumnList.IndexOf(summary.Column);
        if(colIdx == -1)
        {
            return;
        }

        summary.Data = CalculateSummaryData(summary.SummaryDefinition, column);

        if(summary.Control is not null)
        {
            summary.Control.Content = summary.Data;
        }
    }

    #endregion

    #region Refresh

    public CoreTreeNodes<TKey> Nodes { get; set; }

    /// <summary>
    /// Map from _innerTable rows to Data rows.
    /// </summary>
    private Dictionary<CoreRow, CoreRow> _rowMap = new();

    private CoreTable? _innerTable;
    private bool _invalidating = false;

    public void BeforeRefresh()
    {
        if(_summaryRow is not null)
        {
            _summaryRow.Visibility = Visibility.Collapsed;
        }
        _tree.SelectionForeground = GetCellSelectionForegroundBrush();
        _tree.SelectionBackground = GetCellSelectionBackgroundBrush();
    }

    public void RefreshData(CoreTable data)
    {
        var nodes = new CoreTreeNodes<TKey>(NullKey);

        _rowMap.Clear();

        _innerTable = new CoreTable();
        _innerTable.LoadColumns(data.Columns);

        for (var i = 0; i < ActionColumns.Count; i++)
        {
            _innerTable.Columns.Add(
                new CoreColumn
                {
                    ColumnName = $"_ActionColumn{i}",
                    DataType = ActionColumns[i] is DynamicImageColumn
                        ? typeof(BitmapImage)
                        : typeof(String)
                });
        }

        foreach (var row in FilterRows(data.Rows))
        {
            var newRow = _innerTable.NewRow();
            ProcessRow(newRow, row);
            _innerTable.Rows.Add(newRow);
            _rowMap[newRow] = row;

            nodes.Add(GetIDKey(row), GetParentKey(row), newRow);
        }
        nodes.ColumnChanged += Nodes_ColumnChanged;
        Nodes = nodes;
        _tree.ItemsSource = nodes.Nodes;
        if(_summaryRow is not null && Summaries.Count > 0)
        {
            _summaryRow.Visibility = Visibility.Visible;
        }

        CalculateSummaries();

        CalculateRowHeight();
        ResizeColumns(_tree, _tree.ActualWidth - 1, _tree.ActualHeight);

        UpdateRecordCount();
    }

    private void AddRows(IEnumerable<CoreRow> rows, bool clearRows)
    {
        if (_innerTable is null) return;
        _invalidating = true;

        if (clearRows)
        {
            _innerTable.Rows.Clear();
            Nodes.Clear();
            _rowMap.Clear();
        }

        foreach(var row in FilterRows(rows))
        {
            var newRow = _innerTable.NewRow();
            ProcessRow(newRow, row);
            _innerTable.Rows.Add(newRow);
            _rowMap[newRow] = row;

            Nodes.Add(GetIDKey(row), GetParentKey(row), newRow);
        }
        CalculateSummaries();

        CalculateRowHeight();
        UpdateRecordCount();

        _invalidating = false;
    }

    public void AddPage(IEnumerable<CoreRow> page)
    {
        AddRows(page, false);
    }

    private void ProcessRow(CoreRow innerRow, CoreRow row)
    {
        innerRow.LoadValues(row.Values);

        for (var i = 0; i < ActionColumns.Count; i++)
        {
            var ac = ActionColumns[i];
            innerRow[$"_ActionColumn{i}"] = ac.Data(row);
        }
    }

    private void CalculateRowHeight()
    {
        if(_innerTable is not null && _innerTable.Rows.Count > 0)
        {
            var contentHeight = _tree.ActualHeight - (_tree.Padding.Top + _tree.Padding.Bottom) - 2; // Two extra pixels of space
            var targetHeight = contentHeight / _innerTable.Rows.Count;
            _tree.RowHeight = Math.Max(Math.Min(targetHeight, MaxRowHeight), MinRowHeight);
        }
    }

    private void UpdateRecordCount()
    {
        var count = _tree.View != null ? _tree.View.Nodes.Count : Parent.Data.Rows.Count;
        Parent.UpdateRecordCount(count);
    }

    #endregion

    #region Invalidation + Updating

    public void InvalidateRow(CoreRow row)
    {
        _invalidating = true;

        var node = GetNode(row);
        if(node is not null)
        {
            ProcessRow(node.Row, row);
            node.InvalidateData();
        }

        CalculateSummaries();

        _invalidating = false;
    }

    public void UpdateCell(CoreRow row, string column, object? value)
    {
        var node = GetNode(row);
        if(node is not null)
        {
            node[column] = value;
            node.InvalidateData();
        }
    }

    public void UpdateCell(CoreRow row, DynamicColumnBase column)
    {
        var node = GetNode(row);
        if(node is not null)
        {
            if(column is DynamicGridColumn gc)
            {
                node[gc.ColumnName] = row[gc.ColumnName];
            }
            else if(column is DynamicActionColumn ac)
            {
                var i = ActionColumns.IndexOf(ac);
                node[$"_ActionColumn{i}"] = ac.Data(row);
            }
        }
    }

    public void UpdateRow(CoreRow row, CoreTreeNode<TKey> dataRow)
    {
        foreach(var (key, value) in row)
        {
            dataRow[key] = value;
        }
        for (var i = 0; i < ActionColumns.Count; i++)
            dataRow[$"_ActionColumn{i}"] = ActionColumns[i].Data(row);
        dataRow.InvalidateData();
    }

    public void UpdateRow(CoreRow row)
    {
        var dataRow = GetNode(row);
        if(dataRow is not null)
        {
            UpdateRow(row, dataRow);
        }
    }

    #endregion

    public void ScrollIntoView(CoreRow row)
    {
        _tree.ScrollInView(new RowColumnIndex(row.Index + 1, 0));
    }

    #region Direct Edit

    private void _tree_PreviewKeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.OemPeriod)
        {
            if (e.OriginalSource is Syncfusion.Windows.Shared.TimeSpanEdit editor && editor.SelectionStart < 2)
            {
                editor.SelectionStart = 3;
            }
        }
        else if (e.Key == Key.Tab)
        {
            if (Parent.IsDirectEditMode())
            {
                _tree.SelectionController.CurrentCellManager.EndEdit();
                _tree.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
                _tree.SelectionController.CurrentCellManager.BeginEdit();
                e.Handled = true;
            }
        }
        else if(e.Key == Key.Escape)
        {
            if (Parent.IsDirectEditMode())
            {
                bChanged = false;
            }
        }
    }

    private bool bChanged;

    private class DirectEditingObject
    {
        public T Object { get; set; }

        public CoreRow Row { get; set; }

        public CoreTreeNode<TKey>? Node { get; set; }

        public DirectEditingObject(T obj, CoreRow row, CoreTreeNode<TKey>? node)
        {
            Object = obj;
            Row = row;
            Node = node;
        }
    }

    private DirectEditingObject? _editingObject;

    private DirectEditingObject EnsureEditingObject(CoreRow row)
    {
        _editingObject ??= new(Parent.LoadItem(row), row, GetNode(row));
        return _editingObject;
    }

    private void DoEntityChanged(IDynamicColumnBase column, DynamicColumnEntityChangedEventArgs args)
    {
        if (_editingObject is null) return;

        Parent.EntityChanged(_editingObject.Object, _editingObject.Row, args.ColumnName, args.Changes);
    }

    private void UpdateData(string column, Dictionary<CoreColumn, object?> updates)
    {
        if (_editingObject is null)
            return;

        var coreRow = _editingObject.Row;

        try
        {
            Parent.UpdateData(_editingObject.Object, coreRow, column, updates);
        }
        catch(Exception e)
        {
            MessageWindow.ShowError($"Error saving {typeof(T)}", e);
        }
    }
    private void UpdateData(CoreTreeNode<TKey> node, int columnIndex)
    {
        if (GetColumn(columnIndex) is DynamicGridColumn gridcol)
        {
            var datacol = Parent.Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(gridcol.ColumnName));
            if (datacol != null)
            {
                var value = node?[datacol.ColumnName];
                if (value is null)
                    value = CoreUtils.GetDefault(datacol.DataType);
                else
                    value = CoreUtils.ChangeType(value, datacol.DataType);

                UpdateData(datacol.ColumnName, new Dictionary<CoreColumn, object?>() { { datacol, value } });
            }
        }
    }

    private Dictionary<string, CoreTable> _lookups = new();
    private void _tree_CurrentCellBeginEdit(object? sender, TreeGridCurrentCellBeginEditEventArgs e)
    {
        var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
        if (row is null)
            return;

        EnsureEditingObject(row);

        if (_tree.Columns[e.RowColumnIndex.ColumnIndex] is TreeGridComboBoxColumn column && column.ItemsSource == null)
        {
            var gridColumn = GetColumn(e.RowColumnIndex.ColumnIndex);
            if(gridColumn is DynamicGridColumn col)
            {
                var property = col.ColumnName;
                if (col.Editor is ILookupEditor lookupEditor)
                {
                    if (!_lookups.ContainsKey(property))
                        _lookups[property] = lookupEditor.Values(property);
                    var combo = column;
                    combo.ItemsSource = _lookups[property].ToDictionary(_lookups[property].Columns[0].ColumnName, "Display");
                    combo.SelectedValuePath = "Key";
                    combo.DisplayMemberPath = "Value";
                }
            }

        }

        bChanged = false;
    }

    private void Nodes_ColumnChanged(CoreTreeNode<TKey> node, string column)
    {
        if (_invalidating) return;

        var row = GetRow(node);
        if (row is null)
            return;

        var data = Parent.Data;

        var dataCol = Parent.Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(column));
        var col = ColumnList.OfType<DynamicGridColumn>()
            .FirstOrDefault(x => x.ColumnName.Equals(column));
        
        if (col is null || dataCol is null)
            return;

        CalculateSummary(col);

        if (col.Editor is CheckBoxEditor)
        {
            EnsureEditingObject(row);
            if(_editingObject is not null)
            {
                var value = node[column];

                _invalidating = true;
                UpdateData(column, new Dictionary<CoreColumn, object?>() { { dataCol, value } });
                _invalidating = false;
            }

            _editingObject = null;
        }
        if (_editingObject is not null)
            bChanged = true;
    }

    private void _tree_CurrentCellDropDownSelectionChanged(object? sender, CurrentCellDropDownSelectionChangedEventArgs e)
    {
        var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
        if (row is null)
            return;
        EnsureEditingObject(row);
        if ((_editingObject is not null) && (e.SelectedItem is Tuple<object?, string> tuple))
        {
            var gridColumn = GetColumn(e.RowColumnIndex.ColumnIndex);
            if (gridColumn is DynamicGridColumn col)
            {
                var corecol = col.ColumnName;

                var updates = new Dictionary<CoreColumn, object?>();

                var dotIdx = corecol.LastIndexOf('.');
                string prefix, field;
                if(dotIdx == -1)
                {
                    prefix = "";
                    field = corecol;
                }
                else
                {
                    prefix = corecol[..dotIdx];
                    field = corecol[(dotIdx + 1)..];
                }

                if (col.Editor is ILookupEditor editor)
                {
                    var data = editor.Values(corecol);
                    var lookuprow = data.Rows.FirstOrDefault(r => Equals(r[field], tuple.Item1))
                        ?? data.NewRow(true);

                    foreach (CoreColumn lookupcol in data.Columns)
                    {
                        var columnname = String.IsNullOrWhiteSpace(prefix)
                            ? lookupcol.ColumnName
                            : String.Join(".", prefix, lookupcol.ColumnName);
                        var updatecol = Parent.Data.Columns.FirstOrDefault(x => String.Equals(x.ColumnName, columnname));
                        if (updatecol != null)
                            updates[updatecol] = lookuprow[lookupcol.ColumnName];
                    }
                    UpdateData(corecol, updates);
                    bChanged = true;
                }
            }
        }
    }

    private void CancelEdit()
    {
        var obj = _editingObject;
        bChanged = false;
        _editingObject = null;
        _tree.SelectionController.CurrentCellManager.EndEdit(false);
        if(obj is not null)
        {
            UpdateRow(obj.Row, obj.Node);
        }
    }

    private void _tree_CurrentCellEndEdit(object? sender, CurrentCellEndEditEventArgs e)
    {
        if (_editingObject is not null && bChanged)
        {
            UpdateData(_editingObject.Node, e.RowColumnIndex.ColumnIndex);
        }
        if (bChanged)
            Parent.DoChanged();
        bChanged = false;
        _editingObject = null;
    }

    #endregion

    #region Drag + Drop

    private void _tree_DragOver(object sender, DragEventArgs e)
    {
        Parent.DragOver(sender, e);
    }

    private void _tree_Drop(object sender, DragEventArgs e)
    {
        Parent.Drop(sender, e);
    }

    private void RowDragDropController_DragStart(object? sender, TreeGridRowDragStartEventArgs e)
    {
        var rows = e.DraggingNodes.Select(node => MapRow((node.Item as CoreTreeNode<TKey>)?.Row)).NotNull().ToArray();
        Parent.DragStart(sender, rows);
    }

    #endregion
}
