using PCUT.ViewModels;
using System;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Http.Core;
using Http.Core.Extensions;
using static Http.Core.Constants.HttpConstants;
using Http.Core.Exceptions;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace PCUT.Pages
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class UserListPage : Page
    {
        private UserViewModel ViewModels { get; set; }
        public UserListPage()
        {
            this.InitializeComponent();
            ViewModels = DataContext as UserViewModel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ViewModels.Pagination.Page = 1;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            ViewModels.Pagination.Dispose();
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button)
            {
                button.IsEnabled = false;
                Frame.Navigate(typeof(UpsertUserPage));
            }
        }

        private void EditButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.CommandParameter is string userId)
            {
                button.IsEnabled = false;
                if (!string.IsNullOrEmpty(userId))
                    Frame.Navigate(typeof(UpsertUserPage), userId);
                else
                    button.IsEnabled = true;
            }
        }

        private async void PasswordButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.CommandParameter is string userId)
            {
                if (!string.IsNullOrEmpty(userId))
                {
                    var dialog = new ChangePasswordDialog(userId);
                    await dialog.ShowAsync();
                }
            }
        }

        private async void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if(sender is Button button && button.CommandParameter is string userId)
            {
                //Confirm diaglog before delete
                ContentDialog deleteDialog = new ContentDialog
                {
                    Title = "Confirm Delete?",
                    Content = "Are you sure want delete this user?",
                    PrimaryButtonText = "Delete",
                    CloseButtonText = "Cancel"
                };
                deleteDialog.PrimaryButtonStyle = Application.Current.Resources["PrimaryDialogButton"] as Style;
                deleteDialog.CloseButtonStyle = Application.Current.Resources["CloseDialogButton"] as Style;

                var result = await deleteDialog.ShowAsync();
                if (result == ContentDialogResult.Primary)
                {
                    await DeleteUserAsync(userId);
                }
            }
        }

        private async Task DeleteUserAsync(string userId)
        {
            using (var httpClient = HttpClientFactory.CreateClient(ClientNames.ApiClient))
            {
                try
                {
                    var response = await httpClient.DeleteAsync(Api.UserById.FormatRoute(userId));
                    if (response.IsSuccessStatusCode)
                    {
                        await ShowDialog("Delete Success", "User Deleted!");
                        await ViewModels.Reload();
                    }
                    else
                    {
                        await ShowDialog("Error!", "Cant delete user");
                    }
                }
                catch (Exception ex) when (!(ex is AppOutdatedException))
                {
                    await ShowDialog("Error!", $"Got exception: {ex.Message}");
                }
            }
        }

        private async void UnlockDevice_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.CommandParameter is string userId)
            {
                using (var httpClient = HttpClientFactory.CreateClient(ClientNames.ApiClient))
                {
                    try
                    {
                        var response = await httpClient.DeleteAsync(Api.UserUnlockDevice.FormatRoute(userId));
                        if (response.IsSuccessStatusCode)
                        {
                            await ShowDialog("Device Unlock Success", "User's device unlocked!");
                        }
                        else
                        {
                            await ShowDialog("Error!", "Failed to unlock user's device");
                        }
                    }
                    catch (Exception ex) when (!(ex is AppOutdatedException))
                    {
                        await ShowDialog("Error!", $"Got exception: {ex.Message}");
                    }
                }
            }
        }

        private async Task ShowDialog(string title, string content)
        {
            ContentDialog dialog = new ContentDialog
            {
                Title = title,
                Content = content,
                CloseButtonText = "OK"
            };
            dialog.CloseButtonStyle = Application.Current.Resources["CloseDialogButton"] as Style;

            await dialog.ShowAsync();
        }

        private void btnFirst_Click(object sender, RoutedEventArgs e)
        {
            ViewModels.Pagination.Page = 1;
        }

        private void btnLast_Click(object sender, RoutedEventArgs e)
        {
            ViewModels.Pagination.Page = ViewModels.Pagination.TotalPage;
        }

        private void btnPrevious_Click(object sender, RoutedEventArgs e)
        {
            ViewModels.Pagination.Page--;
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            ViewModels.Pagination.Page++;
        }
    }
}
