using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using InABox.Clients;
using InABox.Core;

namespace InABox.DynamicGrid;

public class PopupEditorControl : DynamicEditorControl<Guid, PopupEditor>
{
    
    static PopupEditorControl()
    {
        //DynamicEditorControlFactory.Register<PopupEditorControl, PopupEditor>();
    }
    
    private Type? _type;
    private Guid _value = Guid.Empty;

    private TextBox Editor;
    //public event DefineFilter OnDefineFilter;

    public event OnDefineLookupFilter? OnDefineFilter;

    public override void Configure()
    {
        _type = EditorDefinition.Type;
    }

    protected override FrameworkElement CreateEditor()
    {
        var Grid = new Grid
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            HorizontalAlignment = HorizontalAlignment.Stretch
        };
        Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(30, GridUnitType.Pixel) });
        Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(50, GridUnitType.Pixel) });

        Editor = new TextBox
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            VerticalContentAlignment = VerticalAlignment.Center,
            HorizontalAlignment = HorizontalAlignment.Stretch,
            IsReadOnly = true
        };
        Editor.SetValue(Grid.ColumnProperty, 0);
        Editor.SetValue(Grid.RowProperty, 0);
        Grid.Children.Add(Editor);

        var Select = new Button
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            VerticalContentAlignment = VerticalAlignment.Center,
            HorizontalAlignment = HorizontalAlignment.Stretch,
            Content = "..",
            Margin = new Thickness(5, 0, 0, 0),
            Focusable = false
        };
        Select.SetValue(Grid.ColumnProperty, 1);
        Select.SetValue(Grid.RowProperty, 0);
        Select.Click += Select_Click;
        Grid.Children.Add(Select);

        var Clear = new Button
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            VerticalContentAlignment = VerticalAlignment.Center,
            HorizontalAlignment = HorizontalAlignment.Stretch,
            Content = "Clear",
            Margin = new Thickness(5, 0, 0, 0),
            Focusable = false
        };
        Clear.SetValue(Grid.ColumnProperty, 2);
        Clear.SetValue(Grid.RowProperty, 0);
        Clear.Click += Clear_Click;
        Grid.Children.Add(Clear);

        return Grid;
    }

    private void Select_Click(object sender, RoutedEventArgs e)
    {
        if (_type != null)
        {
            var columns = LookupFactory.DefineLookupColumns(Host.GetEditorType(), _type, ColumnName);
            var list = new PopupList(_type, _value, columns.ColumnNames().ToArray());

            list.OnDefineFilter += t => { return LookupFactory.DefineLookupFilter(Host.GetEditorType(), t, ColumnName, Host.GetItems()); };
            
            list.OnCustomiseGrid += grid =>
            {
                if (EditorDefinition.CanAdd)
                {
                    grid.OnDoubleClick += (o, args) => args.Handled = true; 
                    grid.OnReconfigure += options =>
                    {
                        options.AddRows = Security.CanEdit(_type);
                        options.EditRows = Security.CanEdit(_type);
                        options.EditRows = Security.CanDelete(_type);
                        options.ReadOnly = false;
                    };
                    grid.OnCreateItem += (_, item) =>
                    {
                        LookupFactory.OnCreateItem(Host.GetEditorType(), ColumnName, Host.GetItems(), item);
                    };
                    grid.Reconfigure();
                }
            };

            if (list.ShowDialog() == true)
            {
                _value = list.ID;

                foreach (var col in columns)
                    OtherValues[col.Property] = list.OtherValues[col.Property];
                CheckChanged();

                var display = new List<string?>();
                //var columns = Entity.DefaultLookupColumns(_type) as IColumns;
                foreach (var col in columns)
                    if (list.OtherValues.ContainsKey(col.Property))
                        display.Add(list.OtherValues[col.Property]?.ToString());

                Editor.Text = LookupFactory.FormatLookup(_type, OtherValues, []);
                   // string.Join(" / ", display.Where(x => x != null && !string.IsNullOrWhiteSpace(x.ToString()))));
            }
        }
    }

    private void Clear_Click(object sender, RoutedEventArgs e)
    {
        if (_type != null)
        {
            _value = Guid.Empty;

            var columns = LookupFactory.DefineLookupColumns(Host.GetEditorType(), _type, ColumnName);
            foreach (var col in columns)
                OtherValues[col.Property] = null;

            CheckChanged();
            Editor.Text = "";
        }
    }

    public override int DesiredHeight()
    {
        return 25;
    }

    public override int DesiredWidth()
    {
        return int.MaxValue;
    }

    protected override Guid RetrieveValue()
    {
        return _value;
    }

    protected override void UpdateValue(Guid value)
    {
        _value = value;
        if (_type is null)
        {
            Logger.Send(LogType.Error, "", "PopupEditorControl.UpdateValue(): _type is null!");
            return;
        }

        var client = ClientFactory.CreateClient(_type);
        var columns = LookupFactory.DefineLookupColumns(Host.GetEditorType(), _type, ColumnName);
        var sort = LookupFactory.DefineSort(_type);
        var filter = Filter.Create(_type);
        filter.Property = "ID";
        filter.Operator = Operator.IsEqualTo;
        filter.Value = value;

        var lookup = client.Query(filter, columns, sort);
        var display = new List<object?>();
        if (lookup.Rows.Any())
        {
            Editor.Text = LookupFactory.FormatLookup(Host.GetEditorType(), _type, lookup.Rows.First(), ColumnName);
        }
        else
        {
            Editor.Text = "";
        }
    }

    public override void SetFocus()
    {
        Editor.Focus();
    }

    public override void SetColor(Color color)
    {
        Editor.Background = new SolidColorBrush(color);
    }
}