import 'package:awesome_snackbar_content/awesome_snackbar_content.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' hide Response;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../../Data/Repository/Users/user_repository.dart';
import '../../Helper/Constants/Apiconstants.dart';
import '../../Helper/Logger.dart';
import '../../Model/Response/User/Usermodelresponse.dart';
import '../../View/Authentication/Logiview.dart';
import '../../View/More/Editprofile/Editprofileview.dart';
import '../../View/More/Faqview/faqtabs.dart';
import '../../View/More/Locations/Locationview.dart';
import '../../View/More/Notification/Notificationview.dart';
import '../../View/More/Staffs/Staffview.dart';
import '../Authentication/Authcontroller.dart';

class MoreController extends GetxController{
  String? userName;
  String? userContact;
  String? version;
  String? token;
  String? dialCode;
  String? imageUrl;
  String? header;
  String? locationLabel;
  String? profileLabel;
  String? FAQLabel;
  String? logoutLabel;
  String? actionsLabel;
  String? subscriptionLabel;
  String? paymentsLabel;
  String? communityLabel;
  String? preferencesLabel;
  String? userLabel;
  String? settingsLabel;
  String? notificationsLabel;

  int? versionValue;
  int? roleId;
  int? tenantId;
  int? userId;

  UserDetails? userInfo;
  var describeValue;
  String? currentVersion;


  AuthController authController = Get.put(AuthController());

  UserRepository userRepository = UserRepository();

  String describeCompanyUrl = '${ApiConstants.describeUrl}/51/en_us';

  toUser() {
    if(roleId ==1) {
      Get.to(() => StaffsView());
    }
    else{
      var snackBar = SnackBar(
        elevation: 0,
        behavior: SnackBarBehavior.floating,
        backgroundColor: Colors.transparent,
        content: AwesomeSnackbarContent(
          title: 'Support',
          message: 'Could not view staffs at this moment. Kindly contact app admin.',
          contentType: ContentType.warning,
          color: Colors.red.withAlpha(200),
        ),
      );

      ScaffoldMessenger.of(Get.context!).showSnackBar(snackBar);

    }
  }

  toFaq() {
    Get.to(()=>FaqTabs());
  }

  toSettings() {

  }

  toLocation() {
    Get.to(()=>LocationView());
  }

  toPayment() {}

  toEditProfile() {
    Get.to(()=>EditProfile(data:userInfo,));

  }

  toNotification() {
    Get.to(()=>NotificationView());
  }

  Future<void> confirmLogout(BuildContext context) async {
    final shouldLogout = await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          title: const Text(
            'Confirm Logout',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          content: const Text('Are you sure you want to log out?'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context, false),
              child: const Text('Cancel'),
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.redAccent,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
              onPressed: () => Navigator.pop(context, true),
              child: const Text('Logout'),
            ),
          ],
        );
      },
    );

    if (shouldLogout == true) {
      await toLogin();
    }
  }

  Future<void> toLogin() async {
    print('Logging out user...');
    SharedPreferences prefs = await SharedPreferences.getInstance();

    await prefs.clear(); // Clears all stored keys and values
    authController.loginPhoneNumberController.clear();
    authController.termsChecking = false;

    print('Redirecting to login view...');
    Get.offAll(() => LoginView());
  }



  getToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    token = prefs.getString('tenantFcmToken');
    roleId = prefs.getInt('roleId');
    versionValue = prefs.getInt('versionValue');
    userName = prefs.getString('userName');
    userContact = '+91${prefs.getString('tenantContactNo')}';
    tenantId = prefs.getInt('tenantId');
    userId = prefs.getInt('userId');
    update();
    get(token??'');
  }


  get(String token) async{

    UserModelResponse? result = await userRepository.getUser(token);
    if(result?.status == true){
      getResults(result);
      print('resultprofilecontroller${result?.details?.toJson()}');
    }
  }

  getResults(UserModelResponse? data) {
    // var data = json.encode(userData);
    userInfo = data?.details;
    print('userInfofullname ${userInfo?.fullname}');
    userContact = '+91${data?.details!.contactno}';
    userName = "${data?.details!.fullname.toString()}";
    // imageUrl = "${data.details!.profileimage.toString()}";
    roleId =data?.details!.roleid;
    update();
    if (roleId == 2) {
      // getWeekdayDetails();
    }
  }


  Future<void> getAppVersion() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    PackageInfo packageInfo = await PackageInfo.fromPlatform();

    String version = packageInfo.version;
    currentVersion = version;
    prefs.setString('CurrentVersion', currentVersion!);
    logger.i('Current version from main: $currentVersion');
  }

  @override
  void onInit() {
    // TODO: implement onInit
    getAppVersion();
    super.onInit();
  }
}