//using Android.Content.PM;
using CommunityToolkit.Mvvm.Input;
using GMCabsDriverAssistant.Models;
using GMCabsDriverAssistant.Services;
using GMCabsDriverAssistant.Utils;
using GMCabsDriverAssistantSolution.Models.Rydo;
using GMCabsDriverAssistantSolution.Views;
using Microsoft.Maui.Controls;
using Plugin.FirebasePushNotification;
using Sentry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GMCabsDriverAssistantSolution.ViewModels
{
    public class LoginViewModel : BaseViewModel
    {
        #region Fields
        private string phoneNumber;
        private string message;
        private string pin;
        private double? lat;
        private double? lon;
        private string fcmToken;
        private CancellationTokenSource cts;
        private string installedImei;
        private bool showSupportNumber;
        private bool showInstalledImei;
        private string imeiNumber;
        private string carNumber;
        private readonly bool isTablet;
        #endregion

        #region Properties
        public Command LoginCommand { get; }
        public Command AdminSetUpCommand { get; }
        public string PhoneNumber
        {
            get => phoneNumber;
            set
            {
                SetProperty(ref phoneNumber, value);
                ErrorMessage = string.Empty;
            }
        }
        public string ErrorMessage
        {
            get => message;
            set => SetProperty(ref message, value);
        }
        public string Pin
        {
            get => pin;
            set
            {
                SetProperty(ref pin, value);
                ErrorMessage = string.Empty;
            }
        }
        public string InstalledImei
        {
            get => installedImei;
            set => SetProperty(ref installedImei, value);
        }
        public bool ShowSupportNumber
        {
            get => showSupportNumber;
            set => SetProperty(ref showSupportNumber, value);
        }
        public bool ShowInstalledImei
        {
            get => showInstalledImei;
            set => SetProperty(ref showInstalledImei, value);
        }
        public Command Register { get; set; }
        public Page _page;
        #endregion

        #region Constructor
        public LoginViewModel(Page page)
        {
            isTablet = Preferences.Get("IsTablet", false);
            if (isTablet)
            {
                if (!DependencyService.Resolve<IForegroundService>().IsForeGroundServiceRunning())
                {
                    Preferences.Set("isForeground", "YES");
                    DependencyService.Resolve<IForegroundService>().StartMyForegroundService();
                }
            }
            LoginCommand = new Command(OnLoginClicked);
            Register = new Command(OnRegisterClicked);
            AdminSetUpCommand = new Command(OnAdminSetUpClicked);
            _page = page;
        }
        #endregion

        #region Methods 

        public void LoadDetails()
        {
            imeiNumber = Preferences.Get("imeiNumber", null);
            carNumber = Preferences.Get("carNumber", null);
            InstalledImei = imeiNumber != null && carNumber != null ? imeiNumber + " on Taxi " + carNumber : string.Empty;
            if (isTablet)
            {
                ShowInstalledImei = true;
                ShowSupportNumber = false;
            }
            else
            {
                ShowInstalledImei = false;
                ShowSupportNumber = true;
            }
            GetCurrentLocation();
        }
        public async void GetCurrentLocation()
        {
            try
            {
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
                cts = new CancellationTokenSource();
                var location = await Geolocation.GetLocationAsync(request, cts.Token);

                if (location != null)
                {
                    lat = location.Latitude;
                    lon = location.Longitude;
                }
            }
            catch (Exception ex)
            {
                // Unable to get location
            }
        }

        [Obsolete]
        private async void OnLoginClicked(object obj)
        {
            IsBusy = true;
            ErrorMessage = "";
            //var taxiNumber = Preferences.Get("taxiNumber", null);
            imeiNumber = Preferences.Get("imeiNumber", null);

            GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
            LoginRequestDto loginRequestDto = new LoginRequestDto
            {
                MobileNumber = phoneNumber,
                Pin = pin,
                Latitude = lat ?? lat,
                Longitude = lon ?? lon,
                FCMToken = CrossFirebasePushNotification.Current.Token,
                //FCMToken = "cQvhFgiZSPSq7DtttjvAds:APA91bH09viaCOiSsT2T5yETAyLF6h04wBYFAhb-N1n57GGO5wBshwys-MJfQhjO5QxE648m-JerqWr2xVT3g_CdcclzSQLxOWRHd8mJ5UWj6nGb_lC9E3a3jm21jeMdjEHFosBqbQTU",
                Imei = imeiNumber,
            };
            LoginResponseDto loginResponseDto = new LoginResponseDto();
            loginRequestDto.IsTabletSession = isTablet;
            loginResponseDto = await gmCabsDriverService.Login(loginRequestDto);

            if (loginResponseDto.Token == Guid.Empty)
            {
                IsBusy = false;
                if (!string.IsNullOrEmpty(loginResponseDto.LoginResponseMessage))
                {
                    ErrorMessage = loginResponseDto.LoginResponseMessage;
                }
                else
                {
                    ErrorMessage = "Invalid login. Please retry";
                }
                //_page.Navigation.ShowPopup(new ErrorPopup(ErrorMessage));
            }
            else if (!loginRequestDto.IsTabletSession && loginResponseDto.IsTabletSession)
            {
                IsBusy = false;
                string errorMessage = "Login is already done with the same credential in a tablet, Cannot Login now";
                //_page.Navigation.ShowPopup(new ErrorPopup(errorMessage));
            }
            else
            {
                Preferences.Set("FcmToken", loginRequestDto.FCMToken.ToString());
                Preferences.Set(SecureStorageData.Token, loginResponseDto.Token.ToString());
                Preferences.Set(SecureStorageData.DriverName, loginResponseDto.DriverName.ToString());
                Preferences.Set("DriverMobileNumber", loginResponseDto.DriverMobileNumber.ToString());

                if (Device.RuntimePlatform == Device.Android && isTablet && !string.IsNullOrWhiteSpace(imeiNumber) && !string.IsNullOrWhiteSpace(carNumber))
                {

                    loginResponseDto.CanAcceptBookings = true;
                    loginResponseDto.CanUpdateLicence = false;
                    loginResponseDto.CanScanVouchers = false;
                    loginResponseDto.CanViewCoupons = false;
                    loginResponseDto.CanViewSettings = false;
                    loginResponseDto.CanViewHome = false;
                    loginResponseDto.CanViewJobHistory = true;
                    Preferences.Set(SecureStorageData.CanAcceptBookings, loginResponseDto.CanAcceptBookings);
                    Preferences.Set(SecureStorageData.CanUpdateLicence, loginResponseDto.CanUpdateLicence);
                    Preferences.Set(SecureStorageData.CanScanVouchers, loginResponseDto.CanScanVouchers);
                    Preferences.Set(SecureStorageData.CanViewCoupons, loginResponseDto.CanViewCoupons);
                    Preferences.Set(SecureStorageData.CanViewSettings, loginResponseDto.CanViewSettings);
                    Preferences.Set(SecureStorageData.CanViewHome, loginResponseDto.CanViewHome);
                    Preferences.Set(SecureStorageData.CanViewJobHistory, loginResponseDto.CanViewJobHistory);
                }
                else
                {
                    loginResponseDto.CanViewJobHistory = false;
                    loginResponseDto.CanViewCoupons = true;
                    loginResponseDto.CanViewSettings = true;
                    Preferences.Set(SecureStorageData.CanAcceptBookings, loginResponseDto.CanAcceptBookings);
                    Preferences.Set(SecureStorageData.CanUpdateLicence, loginResponseDto.CanUpdateLicence);
                    Preferences.Set(SecureStorageData.CanScanVouchers, loginResponseDto.CanScanVouchers);
                    Preferences.Set(SecureStorageData.CanViewCoupons, loginResponseDto.CanViewCoupons);
                    Preferences.Set(SecureStorageData.CanViewSettings, loginResponseDto.CanViewSettings);
                    Preferences.Set(SecureStorageData.CanViewHome, loginResponseDto.CanViewHome);
                    Preferences.Set(SecureStorageData.CanViewJobHistory, loginResponseDto.CanViewJobHistory);
                }
                MessagingCenter.Send(this, "LoginSuccessful", loginResponseDto);
                Preferences.Set("UserCode", loginResponseDto.UserCode.ToString());
                if (loginResponseDto.UserCode != Guid.Empty)
                {
                    Preferences.Set(LoginResponseDto.USER_CODE, loginResponseDto.UserCode.ToString());

                    var eftposLoginRequest = new EftposLoginRequest()
                    {
                        DriverId = loginResponseDto.UserCode,
                        MobileNumber = loginResponseDto.DriverMobileNumber
                    };
                    var eftposLoginResponse = await gmCabsDriverService.EftposLogin(eftposLoginRequest);

                    Preferences.Set(EftposLoginResponse.RYDO_ACCESS_TOKEN, eftposLoginResponse.AccessToken);
                    Preferences.Set(EftposLoginResponse.RYDO_TOKEN_TYPE, eftposLoginResponse.TokenType);
                    var driverRatingDetails = await gmCabsDriverService.GetDriverRatings(eftposLoginResponse.AccessToken, loginResponseDto.UserCode.ToString(), loginResponseDto.DriverMobileNumber);
                    if (driverRatingDetails != null)
                    {
                        Preferences.Set("DriverRating", driverRatingDetails.Rating.ToString());
                    }
                }
                //SentrySdk.ConfigureScope(scope =>
                //{
                //    scope.User = new User
                //    {
                //        Id = loginResponseDto.UserCode.ToString()
                //    };
                //});
                PhoneNumber = "";
                Pin = "";
                if (Device.RuntimePlatform == Device.Android && isTablet && !string.IsNullOrWhiteSpace(imeiNumber) && !string.IsNullOrWhiteSpace(carNumber))
                {
                    if (!string.IsNullOrEmpty(loginResponseDto.LoginResponseMessage))
                    {
                        IsBusy = false;
                        ErrorMessage = loginResponseDto.LoginResponseMessage;
                        await Shell.Current.GoToAsync($"//{nameof(LoginPage)}");
                    }
                    else
                    {
                        //await Shell.Current.GoToAsync($"//{nameof(HomePageTablet)}?{nameof(HomePageTabletViewModel.IsBookingConfirmed)}={false}");
                        IsBusy = false;
                    }
                }
                else
                {
                    IsBusy = false;
                    await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
                    //await _page.Navigation.PushAsync(new HomePage());
                    //await Shell.Current.GoToAsync(nameof(HomePage));
                    //await Shell.Current.GoToAsync(nameof(NewPage1));
                }
            }
        }
        private async void OnRegisterClicked(object obj)
        {
            ErrorMessage = "";
            await Shell.Current.GoToAsync($"//{nameof(LoginPage)}/{nameof(UserRegistrationGenerateOtpPage)}");
        }
        private async void OnAdminSetUpClicked(object obj)
        {
            ErrorMessage = "";
            await Shell.Current.GoToAsync($"//{nameof(LoginPage)}/{nameof(AdminPasswordPage)}");
        }
    }
    #endregion  
}
