using GMCabsDriverAssistant.Messages;
using GMCabsDriverAssistant.Models;
using GMCabsDriverAssistant.Services;
using GMCabsDriverAssistant.Utils;
using GMCabsDriverAssistantSolution.ViewModels;
using System.Diagnostics;

namespace GMCabsDriverAssistantSolution.Views;

public partial class NewPage1 : 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
    public NewPage1()
	{
        //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)
    {
        // Navigation.ShowPopup(new AppPermissiontSetDialogPage(this, Constant.FROM_HOME_PAGE));
    }
    #endregion

    #region Methods
    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);
        });
    }
    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);
            //Navigation.ShowPopup(new LoginErrorAlertDialogPage());
        }
    }

    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 void IsSettingRequired()
    {
        if (isLocationPermitted && isBatteryOptimizationDisabled)
        {
            SettingsRequired.IsVisible = false;
        }
        else
        {
            if (Device.RuntimePlatform == Device.iOS && isLocationPermitted)
            {
                SettingsRequired.IsVisible = false;
            }
            else
            {
                SettingsRequired.IsVisible = true;
            }
        }
    }
    private async void OnBookingViewClicked(object sender, EventArgs e)
    {
        //  await Navigation.PushAsync(new BookingsPage(_viewModel.CurrentLocation.Latitude, _viewModel.CurrentLocation.Longitude));
        await DisplayAlert("Success", "Booking view clicked","OK");
    }
    private async void OnNotificationViewClicked(object sender, EventArgs e)
    {
        // await Navigation.PushAsync(new NotificationsPage());
        await DisplayAlert("Success", "Notification view clicked", "OK");
    }
    #endregion
}