using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using InABox.Core;
using InABox.Wpf;

namespace InABox.DynamicGrid;

public partial class PopupList : ThemableWindow
{
    public delegate void CustomiseGridEvent(IDynamicGrid grid);
    public event CustomiseGridEvent? OnCustomiseGrid;

    private readonly Dictionary<string, string>? _filters;

    private IDynamicGrid _grid;
    private readonly string[] _othercolumns = Array.Empty<string>();

    private readonly Type _type;
    private readonly Type? _gridType;

    public PopupList(Type type, Guid id, string[] OtherColumns, Dictionary<string, string>? Filters = null, Type? gridType = null)
    {
        InitializeComponent();

        OtherValues = new Dictionary<string, object?>();

        _filters = Filters;
        _othercolumns = OtherColumns;
        _type = type;
        _gridType = gridType;

        ID = id;

        SourceInitialized += PopupList_SourceInitialized;
    }

    public Guid ID { get; set; }

    public Dictionary<string, object?> OtherValues { get; }

    public string AsLookup()
    {
        var result = new List<object>();
        foreach (var key in OtherValues.Keys.ToArray())
        {
            var comps = key.Split(new[] { "->" }, StringSplitOptions.None);
            result.Add(_grid.SelectedRows.First().Get<object>(comps.First()));
        }

        return string.Join(" / ", result.Where(x => x != null && !string.IsNullOrWhiteSpace(x.ToString())));
    }

    public event OnDefineFilter? OnDefineFilter;

    private void PopupList_SourceInitialized(object? sender, EventArgs e)
    {
        //_grid = DynamicGridUtils.CreateDynamicGrid(typeof(DynamicDataGrid<>), _type);
        _grid = (Activator.CreateInstance(_gridType ?? typeof(DynamicDataGrid<>).MakeGenericType(_type)) as IDynamicGrid)!;
        _grid.Margin = new Thickness(5, 5, 5, 0);
        ((DependencyObject)_grid).SetValue(Grid.ColumnProperty, 0);
        ((DependencyObject)_grid).SetValue(Grid.ColumnSpanProperty, 3);
        ((DependencyObject)_grid).SetValue(Grid.RowProperty, 0);

        //_grid.AddHiddenColumn("AsLookup");
        foreach (var column in _othercolumns)
        {
            var comps = column.Split(new[] { "->" }, StringSplitOptions.None);
            _grid.AddHiddenColumn(comps.First());
            OtherValues[column] = null;
        }

        layoutGrid.Children.Add((UIElement)_grid);
        
        _grid.Reconfigure(options =>
        {
            options.Clear();
            options.SelectColumns = true;
            options.FilterRows = true;
            options.ReadOnly = true;
        });

        if(_grid is IDynamicDataGrid dataGrid)
        {
            dataGrid.ColumnsTag ??= "Popup";
        }

        _grid.OnDefineFilter += t => OnDefineFilter?.Invoke(t);

        _grid.Refresh(true, false);

        if (_filters != null)
            foreach (var key in _filters.Keys)
            {
                // TODO: Get this working again
                _grid.AddVisualFilter(key, _filters[key]);
            }

        OnCustomiseGrid?.Invoke(_grid);

        _grid.Refresh(false, true);

        var screen = WpfScreen.GetScreenFrom(this);
        var maxwidth = (int)screen.WorkingArea.Width - 200;

        var DesiredWidth = _grid.DesiredWidth();
        if (DesiredWidth > maxwidth)
            DesiredWidth = maxwidth;
        if (DesiredWidth > Width)
            Width = DesiredWidth;

        var maxheight = (int)screen.WorkingArea.Height - 200;
        var DesiredHeight = (int)(Width * 0.6);
        if (DesiredHeight > maxheight)
            DesiredHeight = maxheight;
        if (DesiredHeight > Height)
            Height = DesiredHeight;

        _grid.SelectedRows = _grid.Data.Rows.Where(r => r.Get<Guid>("ID").Equals(ID)).ToArray();

        _grid.OnDoubleClick += Grid_OnDoubleClick;
        
        //Left = screen.DeviceBounds.Left + ((screen.DeviceBounds.Width - Width) / 2.0F);
        //Top = screen.DeviceBounds.Top + ((screen.DeviceBounds.Height - Height) / 2.0F);
        //WpfScreen.CenterWindowOnScreen(this);
    }

    private void Grid_OnDoubleClick(object sender, System.ComponentModel.HandledEventArgs args)
    {
        if (_grid.SelectedRows.Any())
            CheckSelectedAndClose();
    }

    private void OKButton_Click(object sender, RoutedEventArgs e)
    {
        if (_grid.SelectedRows.Any())
            CheckSelectedAndClose();
        else
            MessageBox.Show("Please select an Item first");

    }

    private void CheckSelectedAndClose()
    {
        ID = _grid.SelectedRows.First().Get<Guid>("ID");

        //AsLookup = _grid.SelectedRows.First().Get<String>("AsLookup");

        foreach (var key in OtherValues.Keys.ToArray())
        {
            var comps = key.Split(new[] { "->" }, StringSplitOptions.None);
            OtherValues[key] = _grid.SelectedRows.First().Get<object>(comps.First());
        }

        DialogResult = true;
        Close();
    }

    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
        Close();
    }
}