import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:image/image.dart' as img;
import 'package:share_plus/share_plus.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';

import '../../../core/config/server_response.dart';
import '../../../core/constants/app_contants.dart';
import '../../../core/constants/form_field_constants.dart';
import '../../../core/constants/translation_keys.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../core/local_stoarge/app_storage.dart';
import '../../../core/utils/SessionCache.dart';
import '../../../core/utils/fields_utils.dart';
import '../../../core/utils/logs_utils.dart';
import '../../../custom_widgets/Fields/input_field.dart';
import '../../../custom_widgets/custom_button.dart';
import '../../../custom_widgets/custom_dropdown.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../models/DepositAccountResponse.dart';
import '../../../models/upload_user_profile_model.dart';
import '../../../res/app_colors.dart';
import '../../../routes/app_pages.dart';
import '../views/account_details_view.dart';
import '../views/profile_details_view.dart';
import '../views/user_profile_view.dart';

class UserProfileController extends GetxController {
  final AppRepositories repository = Get.find<AppRepositories>();

  static bool isDarkMode = false;
  static RxString cmpCustImage = "".obs;
  static RxString selectedLocale = "en".obs;

  ImagePicker imagePicker = ImagePicker();

  late InputField firstNameField;
  late InputField depositAccountField;
  // static String? profilePic;
  var profilePic = ''.obs;
  List<String> listOfTitles = [
    "Personal Details",
    "Login Name",
    "Mobile Number",
    "Email Address",
  ];
  RxList<DropDown> allDepositAccounts = RxList.empty();

  Rx<DepositAccount> selectedDepositAccount = DepositAccount.empty().obs;

  void updateSelectedDeposit(DropDown item) {
    selectedDepositAccount.value = item.data as DepositAccount;
    dp("Drop Down item View==========", item);
  }

  @override
  void onInit() {
    loadProfilePic();
    super.onInit();

    /// Deposit accounts assign to Drop Down list
    for (int i = 0; i < SessionCache.instance.depositAccountList.length; i++) {
      DepositAccount depositAccount = SessionCache.instance.depositAccountList.elementAt(i);
      dp("=========Desposit All accounts============", depositAccount.toString());
      allDepositAccounts.add(
        DropDown(i.toString(), "${depositAccount.mbmBkmstitle} - ${depositAccount.mbmBkmsnumber}", depositAccount),
      );
    }
  }

  // void uploadUserProfilePicture() async {
  //   if (profilePic == null || profilePic!.isEmpty) {
  //     Toasty.error("Please select an image to upload.");
  //     return;
  //   }
  //
  //   hideKeyBoard();
  //   UploadUserProfileModel request = UploadUserProfileModel(
  //     cmpCustcode: SessionCache.instance.userInfo.cmpCustcode,
  //     porOrgacode: SessionCache.instance.userInfo.porOrgacode,
  //     cmpCustImage: "",
  //   );
  //
  //   ServerResponse response = await repository.uploadUserProfilePicture(request);
  //   if (response.isError) {
  //     Toasty.error(response.errorMsg);
  //     return;
  //   }
  //   cmpCustImage.value = profilePic.value;
  //   Toasty.success("Profile picture updated successfully.");
  // }
  void uploadUserProfilePicture() async {
    if (profilePic.value.isEmpty) {
      Toasty.error("Please select an image to upload.");
      return;
    }

    hideKeyBoard();

    UploadUserProfileModel request = UploadUserProfileModel(
      cmpCustcode: SessionCache.instance.userInfo.cmpCustcode,
      porOrgacode: SessionCache.instance.userInfo.porOrgacode,
      cmpCustImage: profilePic.value,
    );

    ServerResponse response =
    await repository.uploadUserProfilePicture(request);

    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }

    cmpCustImage.value = profilePic.value;

    Toasty.success("Profile picture updated successfully.");
  }

  updateLanguage(Locale locale) async {
    Get.updateLocale(locale);
    // Get.find<LocaleController>().saveLocale(locale.toString());
    // localeController.selectedLocale.value = locale.toString();

    UserProfileController.selectedLocale.value = Get.locale!.languageCode;
    await AppStorage.putString(AppConstants.SELECTED_LOCALE, UserProfileController.selectedLocale.value);
    await AppStorage.putBoolean(AppConstants.IS_RTL, Directionality.of(Get.context!) == TextDirection.rtl);
    Get.forceAppUpdate();
    update();
  }

  void navigateTo(meuType title) {
    if (title == meuType.personalDetails) {
      Get.to(const ProfileDetailsView());
    } else if (title == meuType.bankAccountDetails) {
      Get.to(() => const AccountDetailsView());
    } else if (title == meuType.inviteFriends) {
      //
      Share.share("UCO Digital - Apps on Google Play");
    } else if (title == meuType.changePass) {
      Get.toNamed(Routes.changePassword);
    }
  }

  // void updateProfilePic({required bool fromCamera}) async {
  //   XFile? imageResult;
  //
  //   if (fromCamera) {
  //     imageResult = await imagePicker.pickImage(source: ImageSource.camera);
  //   } else {
  //     imageResult = await imagePicker.pickImage(source: ImageSource.gallery);
  //   }
  //
  //   Get.back();
  //
  //   if (imageResult != null) {
  //     // Read the image file as bytes
  //     Uint8List imageBytes = await imageResult.readAsBytes();
  //
  //     // Check the image size
  //     // double sizeInMB = imageBytes.length / (1024 * 1024);
  //     // if (sizeInMB > 1) {
  //     //   Toasty.error("Image is more than 1MB. Please select a smaller image.");
  //     //   return;
  //     // }
  //
  //     // Decode the image
  //     img.Image? image = img.decodeImage(imageBytes);
  //     if (image != null) {
  //       // Resize the image to reduce its size
  //       img.Image resizedImage = img.copyResize(image, width: 800); // Adjust the width as needed
  //
  //       // Encode the resized image to base64
  //       profilePic.value = base64Encode(img.encodeJpg(resizedImage));
  //
  //       AppStorage.putString(SessionCache.instance.userInfo.cmpUserId, profilePic.value);
  //      // uploadUserProfilePicture();
  //       update();
  //     } else {
  //       Toasty.error("Failed to decode image.");
  //     }
  //   }
  // }
  // void updateProfilePic({required bool fromCamera}) async {
  //   XFile? imageResult;
  //
  //   if (fromCamera) {
  //     imageResult = await imagePicker.pickImage(source: ImageSource.camera);
  //   } else {
  //     imageResult = await imagePicker.pickImage(source: ImageSource.gallery);
  //   }
  //
  //   Get.back();
  //
  //   if (imageResult != null) {
  //     // Read the image file as bytes
  //     Uint8List imageBytes = await imageResult.readAsBytes();
  //
  //     // Decode the image
  //     img.Image? image = img.decodeImage(imageBytes);
  //     if (image != null) {
  //       // Resize the image to reduce its size
  //       img.Image resizedImage = img.copyResize(image, width: 800); // Adjust the width as needed
  //
  //       // Encode the resized image to base64
  //       profilePic = base64Encode(img.encodeJpg(resizedImage)) as RxString;
  //
  //       AppStorage.putString("ProfileImage", profilePic as String);
  //       uploadUserProfilePicture();
  //       update();
  //     } else {
  //       Toasty.error("Failed to decode image.");
  //     }
  //   }
  // }

  void updateProfilePic({required bool fromCamera}) async {
    try {
      XFile? imageResult;

      if (fromCamera) {
        imageResult = await imagePicker.pickImage(
          source: ImageSource.camera,
          imageQuality: 70,
        );
      } else {
        imageResult = await imagePicker.pickImage(
          source: ImageSource.gallery,
          imageQuality: 70,
        );
      }

      Get.back();

      if (imageResult == null) {
        return;
      }

      // Read image bytes
      Uint8List imageBytes = await imageResult.readAsBytes();

      // Decode image
      img.Image? image = img.decodeImage(imageBytes);

      if (image == null) {
        Toasty.error("Failed to decode image.");
        return;
      }

      // Resize image
      img.Image resizedImage = img.copyResize(
        image,
        width: 800,
      );

      // Convert to base64
      String base64Image = base64Encode(
        img.encodeJpg(resizedImage),
      );

      // Update RxString properly
      profilePic.value = base64Image;

      // Save locally
      await AppStorage.putString(
        SessionCache.instance.userInfo.cmpUserId,
        base64Image,
      );

      // Upload API
      uploadUserProfilePicture();

      update();
    } catch (e) {
      dp("Image Error", e.toString());
      Toasty.error("Failed to select image");
    }
  }

  void removeProfilePic() {
    AppStorage.delete(SessionCache.instance.userInfo.cmpUserId);
    profilePic.value = '';
    update();
    Get.back();
  }

  // void loadProfilePic() async {
  //   profilePic.value = await AppStorage.getString(SessionCache.instance.userInfo.cmpUserId);
  //   update();
  //   String? pic = await AppStorage.getString(SessionCache.instance.userInfo.cmpUserId);
  //   profilePic.value = pic;
  //   }
  void loadProfilePic() async {
    String? pic = await AppStorage.getString(
      SessionCache.instance.userInfo.cmpUserId,
    );

    profilePic.value = pic ?? '';

    update();
  }
  void updateName() {
    Get.defaultDialog(
      title: "Update user name",
      contentPadding: const EdgeInsets.only(left: 14, right: 14, bottom: 4),
      content: Column(
        children: [
          const SizedBox(height: 8),
          firstNameField = InputField(
            refKey: FormFieldConstants.instance().getFormKey("nameFeils"),
            controller: FormFieldConstants.instance().getController("firstNameField"),
            hintText: "User Name",
            labelText: TranslationKeys.makeTranslation("User Name"),
            isTopMarginRequired: false,
            showLabel: false,
            inputFormatters: [LengthLimitingTextInputFormatter(FieldUtils.userNameFieldLength)],
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              CustomButton(
                onPressed: () {
                  if (firstNameField.getCustomText().isEmpty) {
                    firstNameField.setError("Enter user name");
                    return;
                  }

                  var newUserDetails = SessionCache.instance.depositAccountList.first.copyWith(mbmBkmstitle: firstNameField.getCustomText());

                  SessionCache.instance.setDepositAccountList([newUserDetails].obs);

                  update();

                  Get.back();
                },
                buttonText: "Update",
                buttonPadding: const EdgeInsets.symmetric(vertical: 5, horizontal: 30),
                textStyle: const TextStyle(fontWeight: FontWeight.w600, fontSize: 16, color: AppColors.black),
                buttonColor: AppColors.colorSkipBtn,
              )
            ],
          ),
        ],
      ),
    );
  }
}
