using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using InABox.Core;
using InABox.Wpf;
using InABox.WPF;
using NPOI.OpenXmlFormats;
using NPOI.SS.Formula.Functions;
using NPOI.Util.Collections;

namespace InABox.DynamicGrid
{
    internal class DynamicVariableGrid : DynamicOneToManyGrid<DigitalForm, DigitalFormVariable>
    {
        private bool ShowHidden = false;
        private Button ShowHiddenButton;
        private Button HideButton;

        protected override void Init()
        {
            base.Init();

            ShowHiddenButton = AddButton("Show Hidden", null, ToggleHidden_Click);
            HideButton = AddButton("Hide Variable", null, Hide_Click);
            HideButton.IsEnabled = false;

            HiddenColumns.Add(x => x.Hidden);
            HiddenColumns.Add(x => x.Code);
            HiddenColumns.Add(x => x.VariableType);
            HiddenColumns.Add(x => x.Parameters);
            HiddenColumns.Add(x => x.Required);
            HiddenColumns.Add(x => x.Secure);
            HiddenColumns.Add(x => x.Retain);
        }

        protected override void DoReconfigure(DynamicGridOptions options)
        {
            base.DoReconfigure(options);

            options.MultiSelect = true;
        }

        public DigitalFormVariable? GetVariable(string code)
        {
            return Items.Where(x => x.Code == code).FirstOrDefault();
        }

        private static bool ShouldHide(CoreRow[] rows)
        {
            return rows.Any(x => !x.Get<DigitalFormVariable, bool>(x => x.Hidden));
        }

        private bool Hide_Click(Button btn, CoreRow[] rows)
        {
            if(rows.Length == 0)
            {
                MessageBox.Show("No rows selected");
                return false;
            }

            var hide = ShouldHide(rows);
            var items = LoadItems(rows);
            foreach (var item in items)
            {
                item.Hidden = hide;
            }
            if(items.Length > 0)
            {
                SaveItems(items);
                return true;
            }
            return false;
        }

        protected override void SelectItems(CoreRow[]? rows)
        {
            base.SelectItems(rows);

            if(rows is null)
            {
                HideButton.IsEnabled = false;
            }
            else
            {
                HideButton.IsEnabled = true;
                HideButton.Content = (ShouldHide(rows) ? "Hide Variable" : "Un-hide Variable") + (rows.Length > 1 ? "s" : "");
            }
        }

        private bool ToggleHidden_Click(Button btn, CoreRow[] rows)
        {
            ShowHidden = !ShowHidden;
            ShowHiddenButton.Content = ShowHidden ? "Hide Hidden" : "Show Hidden";
            return true;
        }

        private void CreateMenu(ContextMenu parent, string header, Type type)
        {
            parent.AddItem(header, null, type, (itemtype) =>
            {
                if(DynamicVariableUtils.CreateAndEdit(Item, Items, itemtype, out var variable))
                {
                    SaveItem(variable);
                    Refresh(false, true);
                }
            });
        }

        protected override void DoAdd(bool openEditorOnDirectEdit = false)
        {
            var menu = new ContextMenu();

            foreach(var fieldType in DFUtils.GetFieldTypes())
            {
                var caption = fieldType.GetCaption();
                if (string.IsNullOrWhiteSpace(caption))
                {
                    caption = CoreUtils.Neatify(fieldType.Name);
                }
                CreateMenu(menu, caption, fieldType);
            }

            menu.IsOpen = true;
        }

        /*public override DigitalFormVariable LoadItem(CoreRow row)
        {
            return Items.FirstOrDefault(r => r.ID.Equals(row.Get<DigitalFormVariable, Guid>(c => c.ID)));
        }*/

        protected override void DoEdit()
        {
            if (!SelectedRows.Any())
                return;
            var variable = LoadItem(SelectedRows.First());
            var properties = variable.CreateProperties();
            if (DynamicVariableUtils.EditProperties(Item, Items, properties.GetType(), properties))
            {
                variable.SaveProperties(properties);
                SaveItem(variable);
                Refresh(false, true);
            }
        }

        protected override void DoDelete()
        {
            var rows = SelectedRows.ToArray();

            if (rows.Any())
                if (CanDeleteItems(rows))
                    if (MessageBox.Show("Are you sure you want to delete this variable? This will all cause data associated with this variable to be lost.\n(If you want to just hide the variable, set it to 'Hidden' instead.)", "Confirm Deletion", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        DeleteItems(rows);
                        SelectedRows = Array.Empty<CoreRow>();
                        DoChanged();
                        Refresh(false, true);
                        SelectItems(null);
                    }
        }

        protected override bool FilterRecord(CoreRow row)
        {
            return ShowHidden || !row.Get<DigitalFormVariable, bool>(x => x.Hidden);
        }
    }

    public class DFLookupFilterNode : ComboBox, ICustomValueNode
    {
        public DFLookupFilterNode(Type entityType, CustomFilterValue? selectedValue)
        {
            var properties = CoreUtils.PropertyList(entityType, x => x.GetCustomAttribute<DoNotSerialize>() == null, true).Keys.ToList();
            properties.Sort();
            Items.Add("");
            foreach (var property in properties)
            {
                Items.Add(property);
            }

            Value = selectedValue;

            SelectionChanged += DFLookupFilterNode_SelectionChanged;

            VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
            VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
            MinWidth = 50;
        }

        private void DFLookupFilterNode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var text = SelectedItem as string;
            if (text.IsNullOrWhiteSpace())
            {
                _value = null;
            }
            else
            {
                _value = new CustomFilterValue(System.Text.Encoding.UTF8.GetBytes(text));
            }
            ValueChanged?.Invoke(this, Value);
        }

        private CustomFilterValue? _value;
        public CustomFilterValue? Value
        {
            get => _value;
            set
            {
                if(value is not null)
                {
                    var text = System.Text.Encoding.UTF8.GetString(value.Data);
                    SelectedItem = text;
                    _value = value;
                }
                else
                {
                    SelectedItem = null;
                    _value = null;
                }
            }
        }

        public FrameworkElement FrameworkElement => this;

        public event ICustomValueNode.ValueChangedHandler? ValueChanged;
    }

    public static class DynamicVariableUtils
    {
        public static bool CreateAndEdit(
            DigitalForm form, IList<DigitalFormVariable> variables,
            Type fieldType,
            [NotNullWhen(true)] out DigitalFormVariable? variable)
        {
            var fieldBaseType = fieldType.GetSuperclassDefinition(typeof(DFLayoutField<>));
            if (fieldBaseType != null)
            {
                var propertiesType = fieldBaseType.GetGenericArguments()[0];
                var properties = (Activator.CreateInstance(propertiesType) as DFLayoutFieldProperties)!;
                if (DynamicVariableUtils.EditProperties(form, variables, propertiesType, properties))
                {
                    variable = new DigitalFormVariable();
                    variable.SaveProperties(fieldType, properties);
                    return true;
                }
            }
            variable = null;
            return false;
        }

        public static bool EditProperties(DigitalForm form, IList<DigitalFormVariable> variables, Type type, DFLayoutFieldProperties item)
        {
            var editor = new DynamicEditorForm(type);
            if (item is DFLayoutLookupFieldProperties)
            {
                var appliesToType = DFUtils.FormEntityType(form);
                editor.OnReconfigureEditors = grid =>
                {
                    var filter = grid.FindEditor("Filter");
                    if(filter is FilterEditorControl filterEditor)
                    {
                        var config = new FilterEditorConfiguration();

                        config.OnCreateCustomValueNode += (type, prop, op, value) =>
                        {
                            if (appliesToType is not null)
                            {
                                return new DFLookupFilterNode(appliesToType, value);
                            }
                            else
                            {
                                return null;
                            }
                        };

                        filterEditor.Configuration = config;
                    }
                };
                editor.OnFormCustomiseEditor += (sender, items, column, editor) => LookupEditor_OnFormCustomiseEditor(sender, variables, items, column, editor);
                editor.OnEditorValueChanged += (sender, name, value) =>
                {
                    var result = DynamicGridUtils.UpdateEditorValue(new[] { item }, name, value);
                    if (name == "LookupType")
                    {
                        var grid = (sender as EmbeddedDynamicEditorForm)?.Editor!;
                        var edit = grid.FindEditor("Filter");
                        if (edit is FilterEditorControl filter)
                        {
                            filter.FilterType = value is string str ?
                                CoreUtils.GetEntityOrNull(str) :
                                null;
                        }

                        var propertiesEditor = grid.FindEditor(nameof(DFLayoutLookupFieldProperties.AdditionalProperties));
                        if (propertiesEditor is MultiLookupEditorControl multi && multi.EditorDefinition is MultiLookupEditor combo)
                        {
                            combo.Clear();
                            multi.Configure();
                        }
                    }
                    return new();
                };
            }
            else
            {
                editor.OnFormCustomiseEditor += (sender, items, column, editor) => Editor_OnFormCustomiseEditor(sender, variables, column, editor);
                editor.OnEditorValueChanged += (sender, name, value) =>
                {
                    return DynamicGridUtils.UpdateEditorValue(new[] { item }, name, value);
                };
            }

            editor.OnDefineLookups += o =>
            {
                var def = (o.EditorDefinition as ILookupEditor)!;
                var colname = o.ColumnName;
                // Nope, there is nothing dodgy about this at all
                // I am not breaking any rules by passing in the QA Form instance, rather than the Field instance 
                // so that I can get access to the "AppliesTo" property, and thus the list of properties that can be updated
                // Nothing to see here, I promise!
                CoreTable? values;
                if (o.ColumnName == "Property")
                {
                    values = def.Values(colname, new[] { form });
                }
                else
                {
                    values = def.Values(colname, new[] { item });
                }

                o.LoadLookups(values);
            };

            var thisVariable = variables.Where(x => x.Code == item.Code).ToList();

            editor.OnValidateData += (sender, items) =>
            {
                var errors = new List<string>();
                foreach(var item in items.Cast<DFLayoutFieldProperties>())
                {
                    if (string.IsNullOrWhiteSpace(item.Code))
                    {
                        errors.Add("[Code] may not be blank!");
                    }
                    else
                    {
                        var codeVars = variables.Where(x => x.Code == item.Code).ToList();
                        if(codeVars.Count > 1)
                        {
                            errors.Add($"Duplicate code [{item.Code}]");
                        }
                        else if(codeVars.Count == 1)
                        {
                            if (!thisVariable.Contains(codeVars.First()))
                            {
                                errors.Add($"There is already a variable with code [{item.Code}]");
                            }
                        }
                    }
                }
                return errors;
            };
            editor.Items = new BaseObject[] { item };
            return editor.ShowDialog() == true;
        }

        private static void Editor_OnFormCustomiseEditor(IDynamicEditorForm sender, IList<DigitalFormVariable> vars, DynamicGridColumn column, BaseEditor editor)
        {
            if ((column.ColumnName == "Expression" || column.ColumnName == "ColourExpression") && editor is ExpressionEditor exp)
            {
                var variables = new List<string>();
                foreach (var variable in vars)
                {
                    //variables.Add(variable.Code);
                    foreach (var col in variable.GetVariableColumns())
                    {
                        variables.Add(col.ColumnName);
                    }
                }
                variables.Sort();
                exp.VariableNames = variables;
            }
        }

        private static void LookupEditor_OnFormCustomiseEditor(IDynamicEditorForm sender, IList<DigitalFormVariable> vars, object[] items, DynamicGridColumn column, BaseEditor editor)
        {
            if (column.ColumnName == "Filter" && editor is FilterEditor fe)
            {
                var properties = (items[0] as DFLayoutLookupFieldProperties)!;
                var lookupType = properties.LookupType;
                var entityType = CoreUtils.GetEntityOrNull(lookupType);
                fe.Type = entityType;
            }
            Editor_OnFormCustomiseEditor(sender, vars, column, editor);
        }

    }
}