using CommunityToolkit.Maui.Views;
using GMCabsDriverAssistant.Messages;
using GMCabsDriverAssistant.Models;
using GMCabsDriverAssistant.Services;
using GMCabsDriverAssistant.Utils;
using GMCabsDriverAssistantSolution.Models.Rydo;
using GMCabsDriverAssistantSolution.ViewModels;
using Sentry;
using System.Diagnostics;
using System.Text.Json;

namespace GMCabsDriverAssistantSolution.Views;

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : ContentPage
{
    #region Fields
    private readonly HomeViewModel _viewModel;
    bool isLocationPermitted, isBatteryOptimizationDisabled;
    #endregion

    #region Properties
    public double CurrentLat { get; set; }
    public double CurrentLng { get; set; }
    #endregion

    #region Constructor
    [Obsolete]
    public HomePage()
    {
        //SentrySdk.CaptureMessage(nameof(HomePage));

        InitializeComponent();
        BindingContext = _viewModel = new HomeViewModel();

        MessagingCenter.Unsubscribe<App, string>(this, nameof(App));
        MessagingCenter.Subscribe<App, string>(this, nameof(App), async (sender, args) =>
        {
            Debug.WriteLine($"args: {args}");
            if (args == "DriverAlertNotification")
            {
                await _viewModel.UpdateLocation();
            }
            else
            {
              await  _viewModel.OnAppearing();
            }


        });

        //handle canceling of an accepted booking
        MessagingCenter.Unsubscribe<App, CancelledBookingResponseDto>(this, nameof(App));
        MessagingCenter.Subscribe<App, CancelledBookingResponseDto>(this, nameof(App), async (sender, args) =>
        {
            await Navigation.PopToRootAsync();
            //await Shell.Current.GoToAsync($"{nameof(CancelledBookingPage)}?{nameof(CancelledBookingViewModel.PickUpAddress)}={args.PickUPAddress}&{nameof(CancelledBookingViewModel.DropUpAddress)}={args.DropUpAddress}");
            _viewModel.IsVisibleAcceptBookingView = false;
        });
        //MessagingCenter.Unsubscribe<AcceptBookingPage, AcceptBookingTimerDto>(this, nameof(AcceptBookingPage));
        //MessagingCenter.Subscribe<AcceptBookingPage, AcceptBookingTimerDto>(this, nameof(AcceptBookingPage), (sender, args) =>
        //{
        //    _viewModel.seconds = args.PendingSeconds;
        //    _viewModel.PickUpAddress = args.PickUPAddress;
        //    _viewModel.DropUpAddress = args.DropUpAddress;
        //    if (_viewModel.seconds > 0)
        //    {
        //        _viewModel.IsVisibleAcceptBookingView = true;
        //    }
        //});

        // handle clearing of an accepted booking
        MessagingCenter.Unsubscribe<App, string>(this, "ClearAcceptance");
        MessagingCenter.Subscribe<App, string>(this, "ClearAcceptance", async (sender, args) =>
        {
            await Navigation.PopToRootAsync();
            _viewModel.IsVisibleAcceptBookingView = false;
            _viewModel.seconds = 0;
        });
        //MessagingCenter.Unsubscribe<AcceptBookingPage, string>(this, "ClearAcceptance");
        //MessagingCenter.Subscribe<AcceptBookingPage, string>(this, "ClearAcceptance", async (sender, args) =>
        //{
        //    await Navigation.PopToRootAsync();
        //    await Shell.Current.GoToAsync($"{nameof(HomePage)}");
        //    _viewModel.IsVisibleAcceptBookingView = false;
        //    _viewModel.seconds = 0;
        //});

        // Used to handle notification by using MessagingCenter same is tablet based notification system
        MessagingCenter.Subscribe<App, string>(this, nameof(App), (sender, args) =>
        {
            _viewModel.GetUnreadNotificationCount();
        });
        MessagingCenter.Subscribe<App, NotificationDto>(this, nameof(App), async (sender, notification) =>
        {
            _viewModel.GetUnreadNotificationCount();
        });
    }

    #endregion

    #region Events
    private void SettingsRequired_Tapped(object sender, EventArgs e)
    {
        this.ShowPopup(new AppPermissiontSetDialogPage(this, Constant.FROM_HOME_PAGE));        
    }
    #endregion

    #region Methods
    [Obsolete]
    protected override void OnAppearing()
    {
        base.OnAppearing();
        //CheckAppPermissionStatus();
        isLocationPermitted = Preferences.Get(SecureStorageData.IsLocationPermitted, false);
        isBatteryOptimizationDisabled = Preferences.Get(SecureStorageData.IsBatteryOptimizationDisabled, false);
        IsSettingRequired();
        GoToLoginPage();
        Task.Run(async () =>
        {
            GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
            await _viewModel.OnAppearing();
            DisplayBookingOrNotification(_viewModel.HasUnreadNotifications, _viewModel.IsBookingAvailable, _viewModel.availableBookingIDs);
        });
    }

    [Obsolete]
    private async void CheckAppPermissionStatus()
    {
        var status = await Permissions.CheckStatusAsync<Permissions.LocationAlways>();
        if (status == PermissionStatus.Granted)
        {
            Preferences.Set(SecureStorageData.IsLocationPermitted, true);
        }
        else
        {
            Preferences.Set(SecureStorageData.IsLocationPermitted, false);
        }
        if (Device.RuntimePlatform == Device.Android)
        {
            if (DependencyService.Get<IBatteryInfo>().CheckIsIgnoringBatteryOptimizations())
            {
                Preferences.Set(SecureStorageData.IsBatteryOptimizationDisabled, true);
            }
            else
            {
                Preferences.Set(SecureStorageData.IsBatteryOptimizationDisabled, false);
            }
        }
    }

    private async void GoToLoginPage()
    {
        ValidateTokenResponseDto validateTokenResponseDto = new ValidateTokenResponseDto();
        GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
        var token = Preferences.Get(SecureStorageData.Token, "");
        var fcmToken = Preferences.Get("FcmToken", "");
        validateTokenResponseDto = await gmCabsDriverService.ValidateAuthToken(token, fcmToken);
        if (!validateTokenResponseDto.Result)
        {
            var message = new StopServiceMessage();
            MessagingCenter.Send(message, "ServiceStopped");
            var lastLatitude = Convert.ToDouble(Preferences.Get("lastLat", "0"));
            var lastLongitude = Convert.ToDouble(Preferences.Get("lastLng", "0"));
            await gmCabsDriverService.LogoutDriverApp(token, lastLatitude, lastLongitude);
            this.ShowPopup(new LoginErrorAlertDialogPage());
        }
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        _viewModel.OnDisappearing();
    }

    private async void OnNotificationViewClicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new NotificationsPage());
    }
    private async void OnBookingViewClicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new BookingsPage(_viewModel.CurrentLocation.Latitude, _viewModel.CurrentLocation.Longitude));
    }

    [Obsolete]
    private async void DisplayBookingOrNotification(bool HasUnreadNotifications, bool IsBookingAvailable, List<Guid> availableBookingIDs)
    {
        if (isLocationPermitted)
        {
            var currentLocation = Geolocation.GetLastKnownLocationAsync();
            CurrentLat = currentLocation.Result.Latitude;
            CurrentLng = currentLocation.Result.Longitude;
            var isInitLaunched = Preferences.Get(SecureStorageData.InitLaunched, "");
            if (String.IsNullOrEmpty(isInitLaunched))
            {
                Preferences.Set(SecureStorageData.InitLaunched, "1");
                if (HasUnreadNotifications && !IsBookingAvailable)
                {
                    //open notification page
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        Navigation.PushAsync(new NotificationsPage());
                    });
                }
                else if (!HasUnreadNotifications && IsBookingAvailable && availableBookingIDs != null && availableBookingIDs.Count == 1)
                {
                    string bookingJson = "";
                    string rydoAccessToken = Preferences.Get(EftposLoginResponse.RYDO_ACCESS_TOKEN, "");
                    Guid driverId = Guid.Parse(Preferences.Get(LoginResponseDto.USER_CODE, ""));

                    GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
                    var bookings = await gmCabsDriverService.GetBookings(rydoAccessToken, driverId, CurrentLat, CurrentLng);
                    if (bookings.Count > 0)
                    {
                        if (bookings.Exists(x => x.BookingId == availableBookingIDs.First()))
                        {
                            bookingJson = JsonSerializer.Serialize(bookings.Single(x => x.BookingId == availableBookingIDs.First()));
                        }
                        else
                        {
                            bookingJson = JsonSerializer.Serialize(bookings.First());
                        }

                        Device.BeginInvokeOnMainThread(async () =>
                        {
                            await Shell.Current.GoToAsync($"{nameof(BookingDetailsPage)}?{nameof(BookingDetailViewModel.BookingJson)}={bookingJson}");
                        });
                    }
                }
            }
        }
    }

    [Obsolete]
    private void IsSettingRequired()
    {
        if (isLocationPermitted && isBatteryOptimizationDisabled)
        {
            SettingsRequired.IsVisible = false;
        }
        else
        {
            if (Device.RuntimePlatform == Device.iOS && isLocationPermitted)
            {
                SettingsRequired.IsVisible = false;
            }
            else
            {
                SettingsRequired.IsVisible = true;
            }
        }
    }
    #endregion

}