using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using InABox.Core;
using InABox.Wpf;
using InABox.WPF;
using Syncfusion.Windows.Shared;
using Syncfusion.Windows.Tools.Controls;

namespace InABox.DynamicGrid;

public class DynamicEditorFormModel
{
    /// <summary>
    ///     Constructor of the UtilityViewModel class.
    /// </summary>
    public DynamicEditorFormModel()
    {
        var utilities = new ObservableCollection<UtilityItem>();
        utilities.Add(new UtilityItem
            { Name = "Help", Icon = Resources.help.AsBitmapImage(), Text = "", Mode = SizeMode.Normal, Command = HelpCommand });
        Utilities = utilities;
    }

    /// <summary>
    ///     Collection containing the complete details of the items to be bound in the title bar.
    /// </summary>
    public ObservableCollection<UtilityItem> Utilities { get; }

    /// <summary>
    ///     Commmand for the Help button.
    /// </summary>
    public DelegateCommand HelpCommand => new(HelpCommandAction);

    public static string Slug { get; set; }

    /// <summary>
    ///     Action that is performed when clicking the help button.
    /// </summary>
    private void HelpCommandAction(object param)
    {
        Process.Start("https://prsdigital.com.au/wiki/index.php/" + Slug);
    }
}

/// <summary>
///     Interaction logic for DynamicEditor.xaml
/// </summary>
public partial class DynamicEditorForm : ThemableChromelessWindow, IDynamicEditorForm, ISubPanel
{
    #region IDynamicEditorForm

    public bool ReadOnly { get => Form.ReadOnly; set => Form.ReadOnly = value; }
    public BaseObject[] Items
    {
        get => Form.Items;
        set
        {
            Form.Items = value;
        }
    }
    public DynamicEditorPages? Pages { get => Form.Pages; }

    public event OnBeforeLoad? OnBeforeLoad;
    public void BeforeLoad() => OnBeforeLoad?.Invoke(this);

    public event OnAfterLoad? OnAfterLoad;
    public void AfterLoad() => OnAfterLoad?.Invoke(this);

    public event OnValidateData? OnValidateData { add => Form.OnValidateData += value; remove => Form.OnValidateData -= value; }

    public OnCustomiseColumns? OnCustomiseColumns
    {
        get => Form.OnCustomiseColumns; 
        set => Form.OnCustomiseColumns = value;
    }
    public OnDefineLookupFilter? OnDefineFilter { get => Form.OnDefineFilter; set { Form.OnDefineFilter = value; } }

    public OnDefineLookup? OnDefineLookups { get => Form.OnDefineLookups; set { Form.OnDefineLookups = value; } }

    public DefineEditorEventHandler? OnDefineEditor { get => Form.OnDefineEditor; set { Form.OnDefineEditor = value; } }
    public event OnFormCustomiseEditor? OnFormCustomiseEditor { add => Form.OnFormCustomiseEditor += value; remove => Form.OnFormCustomiseEditor -= value; }

    public OnReconfigureEditors? OnReconfigureEditors { get => Form.OnReconfigureEditors; set { Form.OnReconfigureEditors = value; } }

    public event OnCreateEditorControl? OnCreateEditorControl { add => Form.OnCreateEditorControl += value; remove => Form.OnCreateEditorControl -= value; }
    
    public event OnAfterEditorValueChanged? OnAfterEditorValueChanged { add => Form.OnAfterEditorValueChanged += value; remove => Form.OnAfterEditorValueChanged -= value; }
    public event EditorValueChangedHandler? OnEditorValueChanged { add => Form.OnEditorValueChanged += value; remove => Form.OnEditorValueChanged -= value; }


    public event OnSelectPage? OnSelectPage { add => Form.OnSelectPage += value; remove => Form.OnSelectPage -= value; }

    public DynamicGridSaveEvent? OnSaveItem { get => Form.OnSaveItem; set { Form.OnSaveItem = value; } }

    public event IDynamicEditorForm.OnReloadEventHandler? OnReload { add => Form.OnReload += value; remove => Form.OnReload -= value; }

    public bool TryFindEditor(string columnname, [NotNullWhen(true)] out IDynamicEditorControl? editor) => Form.TryFindEditor(columnname, out editor);

    public object? GetEditorValue(string columnName) => Form.GetEditorValue(columnName);
    public void SetEditorValue(string columnName, object? value) => Form.SetEditorValue(columnName, value);

    public void UnloadEditorPages(bool saved) => Form.UnloadEditorPages(saved);

    #endregion

    public bool? Result { get; set; }

    public DynamicEditorForm()
    {
        InitializeComponent();
        Form.OnEditorCreated += Editor_OnEditorCreated;
        Form.OnOK += Form_OnOK;
        Form.OnCancel += Form_OnCancel;
    }

    public DynamicEditorForm(Type type, DynamicEditorPages? pages = null, DynamicEditorButtons? buttons = null,
        Func<Type, CoreTable>? pageDataHandler = null, bool preloadPages = false): this()
    {
        Setup(type, pages, buttons, pageDataHandler, preloadPages);
    }

    public void Setup(Type type, DynamicEditorPages? pages = null, DynamicEditorButtons? buttons = null,
        Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
    {
        Form.Setup(type, pages, buttons, pageDataHandler, preloadPages);
    }
    public void SetLayoutType<T>() where T : DynamicEditorGridLayout => Form.SetLayoutType<T>();
    public void SetLayout(DynamicEditorGridLayout layout) => Form.SetLayout(layout);

    // Providing new implementation to avoid using DIalogResult, which breaks if non-modal.
    public new bool? ShowDialog()
    {
        base.ShowDialog();
        return Result;
    }

    private void Form_OnCancel()
    {
        if (bChanged)
        {
            var result = MessageWindow.ShowYesNoCancel("Save Changes?", "Confirm");
            switch (result)
            {
                case MessageWindowResult.Yes:
                    Result = true;
                    Close();
                    break;
                case MessageWindowResult.No:
                    Result = false;
                    Close();
                    break;
            }
        }
        else
        {
            Result = false;
            Close();
        }
    }

    private void Form_OnOK()
    {
        Result = true;
        Close();
    }

    private void Editor_OnEditorCreated(object sender, double height, double width)
    {
    }

    private void Window_Closing(object sender, CancelEventArgs e)
    {
        if (bChanged && Result == null)
        {
            var result = MessageWindow.ShowYesNoCancel("Save Changes?", "Confirm");
            switch (result)
            {
                case MessageWindowResult.Yes:
                    Result = true;
                    break;
                case MessageWindowResult.No:
                    Result = false;
                    break;
                case MessageWindowResult.Cancel:
                    e.Cancel = true;
                    return;
            }
        }
        if (Result == true)
            Form.SaveItem(e);
        SubPanelClosed?.Invoke(this);
    }

    private bool bChanged = false;
    private void Form_OnOnChanged(object? sender, EventArgs e)
    {
        bChanged = true;
    }

    private void Form_OnReload(IDynamicEditorForm form)
    {
        SetSize();
    }

    private void SetSize()
    {
        var screen = WpfScreen.GetScreenFrom(new Point(Left, Top));

        double spareheight = 90;
        double sparewidth = 25;

        var desiredheight = Form.ContentHeight + spareheight;
        var desiredwidth = Form.ContentWidth + sparewidth;

        var oldHeight = Height;

        var maxheight = screen.WorkingArea.Height - 300;
        Height = desiredheight > maxheight ? maxheight : desiredheight;
        Top += (oldHeight - Height) / 2;

        var maxwidth = screen.WorkingArea.Width - 0;
        Width = desiredwidth > maxwidth ? maxwidth : desiredwidth;

        var scaption = Form.Items[0].GetType().GetCaption();
        Title = "Edit " + scaption.SplitCamelCase();
    }

    #region ISubPanel

    public event ISubPanel.ClosedEvent? SubPanelClosed;

    void ISubPanel.Shutdown(CancelEventArgs? cancel)
    {
        if (bChanged)
        {
            this.Focus();
            var window = cancel is null
                ? MessageWindow.NewYesNo($"You have unsaved changes: do you wish to save this {CoreUtils.Neatify(Form.Items[0].GetType().GetCaption())}?", "Save changes?")
                : MessageWindow.NewYesNoCancel($"You have unsaved changes: do you wish to save this {CoreUtils.Neatify(Form.Items[0].GetType().GetCaption())}?", "Save changes?");
            var result = window.Display().Result;
            switch (result)
            {
                case MessageWindowResult.Yes:
                    Result = true;
                    Close();
                    break;
                case MessageWindowResult.No:
                    Result = false;
                    Close();
                    break;
                case MessageWindowResult.Cancel:
                    if(cancel is not null)
                    {
                        cancel.Cancel = true;
                    }
                    return;
            }
        }
        else
        {
            Close();
        }
    }

    #endregion

    private void ThemableChromelessWindow_Loaded(object sender, RoutedEventArgs e)
    {
        SetSize();
    }
}