using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using InABox.Mobile.Shared;
using Syncfusion.XForms.Core;
using Syncfusion.XForms.PopupLayout;
using Xamarin.CommunityToolkit.UI.Views;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XF.Material.Forms.UI.Dialogs;

namespace InABox.Mobile
{

    // public class BackButtonClickedEventArgs : CancelEventArgs
    // {
    //     
    // }
    //
    // public delegate void BackButtonClickedEvent(object sender, BackButtonClickedEventArgs args);
    
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MobilePage 
    {
        public static IModelHost Host { get; set; }
        
        public IList<View> AlternateMenu => _alternateMenu.Children;
        
        public IList<View> PrimaryMenu => _primaryMenu.Children;
        
        public IList<View> PageContent => _content.Children;

        public bool BackButtonEnabled
        {
            get => _backButton.IsVisible;
            set => _backButton.IsVisible = value;
        }
        
        public MobilePage()
        {
            InitializeComponent();
            activity_indicator.BackgroundColor = XF.Material.Forms.Material.Color.Primary;
            activity_indicator.TextColor = XF.Material.Forms.Material.Color.OnPrimary;
            _titleBar.BackgroundColor = XF.Material.Forms.Material.Color.Primary;
            _titleLabel.TextColor = XF.Material.Forms.Material.Color.OnPrimary;
            BackgroundColor = Color.WhiteSmoke;
        }
        
        protected override void OnAppearing()
        {
            ProgressVisible = false;
            
            XF.Material.Forms.Material.PlatformConfiguration.ChangeStatusBarColor(XF.Material.Forms.Material.Color.PrimaryVariant);
            
            UpdateBackgroundUpdateStatus();
            Host.BackgroundUpdateStatusChanged += BackgroundUpdateStatusChanged;

            UpdateTransportStatus();
            Host.TransportConnected += TransportConnected;
            Host.TransportDisconnected += TransportDisconnected; 
            
            base.OnAppearing();
            
        }
        
        protected override void OnDisappearing()
        {
            ProgressVisible = false;
            Host.BackgroundUpdateStatusChanged -= BackgroundUpdateStatusChanged;
            Host.TransportConnected -= TransportConnected;
            Host.TransportDisconnected -= TransportDisconnected;
            base.OnDisappearing();
        }

        private void TransportDisconnected(TransportDisconnectedEventArgs args) => UpdateConnectionStatus();

        private void TransportConnected(TransportConnectedEventArgs args) => UpdateConnectionStatus();
        
        private void UpdateConnectionStatus()
        {
            Device.BeginInvokeOnMainThread(UpdateTransportStatus);
        }
        
        protected virtual void UpdateTransportStatus()
        {
            _connectionIndicator.IsVisible = !Host.IsConnected();
        }
        
        private void BackgroundUpdateStatusChanged(object sender, EventArgs args)
        {
            Device.BeginInvokeOnMainThread(UpdateBackgroundUpdateStatus);
        }

        private void UpdateBackgroundUpdateStatus()
        {
            _updateIndicator.IsVisible = Host.IsBackgroundUpdateStatusActive;
        }

        private async void _backButton_OnClicked(object sender, EventArgs e)
        {

            if (await OnBackButtonClicked())
                Navigation.PopAsync();

            // if (OnBackButtonPressed())
            // {
            //     if (await ConfirmChanges())
            //     var args = new BackButtonClickedEventArgs() { Cancel = false };
            //     BackButtonClicked?.Invoke(this, args);
            //     if (!args.Cancel)
            //         
            // }
        }
        
        protected virtual async Task<bool> OnBackButtonClicked()
        {
            return true;
        }
        
        protected async Task<bool> ConfirmChanges(IShell item)
        {
            if (item.IsChanged())
            {
                var choice = await MaterialDialog.Instance.SelectActionAsync("Confirm Cancel?",
                    new string[] { "Yes, Cancel", "Keep Editing", "Save Changes" });
                if (choice == 0)
                    item.Cancel();
                else if (choice == 2)
                    item.Save("Saved on Mobile Device");
                else // Cancel (choice==1) or Tap outside box
                    return false;
                Dispatcher.BeginInvokeOnMainThread(() => Navigation.PopAsync());
                return false;
            }
            return true;
        }
        
        protected void ShowPopup(Func<View> view, PopupManagerConfiguration config = null) 
            => PopupManager.ShowPopup(this, view, config);
        
        protected void DismissPopup() 
            => PopupManager.DismissPopup();

        public bool ProgressVisible
        {
            get => activity_indicator.IsBusy;
            set
            {
                activity_frame.IsVisible = value;
                activity_indicator.IsBusy = value;
            }
        }
    }
}