import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../core/config/server_response.dart';
import '../../../core/constants/app_contants.dart';
import '../../../core/constants/translation_keys.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../core/enums/request_constants.dart';
import '../../../core/local_stoarge/app_storage.dart';
import '../../../core/utils/SessionCache.dart';
import '../../../core/utils/app_utils.dart';
import '../../../core/utils/logs_utils.dart';
import '../../../custom_widgets/Fields/field_validations.dart';
import '../../../custom_widgets/Fields/input_field.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../models/AuthenticationRequest.dart';
import '../../../models/finger_print_info.dart';
import '../../../routes/app_pages.dart';
import '../../app_setting/controllers/app_setting_controller.dart';

class LoginScreenController extends GetxController {
  BuildContext context = Get.context as BuildContext;
  final AppRepositories repository = Get.find<AppRepositories>();
  late InputField userNameInputField;
  late InputField passwordInputField;
  bool loginUsingFingerPrint = false;

  @override
  Future<void> onReady() async {
    super.onReady();

    if (kDebugMode) {
      /// Ciihive server
      // userNameInputField.setText("duck@gmail.com");
      // passwordInputField.setText("Test@123");

      /// Local server
      // userNameInputField.setText("nabeelx64@gmail.com");
      // passwordInputField.setText("App@123");
    }
  }

  updateLanguage(Locale locale) async {
    Get.updateLocale(locale);
    // Get.find<LocaleController>().saveLocale(locale.toString());
    // localeController.selectedLocale.value = locale.toString();
    AppSettingController.isRTL.value = Get.locale!.languageCode == "ar" || Get.locale!.languageCode == "ur";
    AppSettingController.selectedLocale.value = Get.locale!.languageCode;
    await AppStorage.putString(AppConstants.SELECTED_LOCALE, AppSettingController.selectedLocale.value);
    await AppStorage.putBoolean(AppConstants.IS_RTL, AppSettingController.isRTL.value);
    Get.forceAppUpdate();
    update();
  }

  bool validate() {
    bool isValid = FieldValidation.validateAll([userNameInputField, passwordInputField]);
    return isValid;
  }

  void validateAndLogin() async {


    if (!validate()) {
      Toasty.error("Please input and then proceed");
      return;
    }
    if (!AppUtils.isPasswordValid(passwordInputField.getCustomText(), 8)) {
      Toasty.error(
          TranslationKeys.makeTranslation(TranslationKeys.textPasswordPattern));
      return;
    }

    AuthenticationRequest request = AuthenticationRequest(
      email: userNameInputField.getCustomText(),
      password: passwordInputField.getCustomText(),
      channelCode: RequestConstants.channelCode,
      porOrgacode: RequestConstants.porOrgacode,
      isOtpRequired: false,
    );

    ServerResponse response = await repository.login(request);
    dp("server response", response);
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }

    Get.toNamed(Routes.O_T_P_SCREEN,
      arguments: {AppConstants.SIGN_UP_FIRST_STEP_DATA: request});
  }

  void fingerPrintLogin() async {
    String info = await AppStorage.getString(AppConstants.IS_FINGER_PRINT_ENABLED, fallback: "");
    if (info.isEmpty) {
      Toasty.error(TranslationKeys.makeTranslation(TranslationKeys.textInvalidFingerprint));
      AppStorage.putString(AppConstants.IS_FINGER_PRINT_ENABLED, "");
      return;
    }

    FingerPrintInfo fingerPrintInfo = FingerPrintInfo.fromMap(jsonDecode(info));

    if (fingerPrintInfo.cmpUserId.isEmpty || fingerPrintInfo.cmpCustpassword.isEmpty) {
      Toasty.error(TranslationKeys.makeTranslation(TranslationKeys.textInvalidFingerprint));

      AppStorage.putString(AppConstants.IS_FINGER_PRINT_ENABLED, "");

      return;
    }

    SessionCache.instance.fingerPrintController.authenticate((status) async {
      if (status) {
        AuthenticationRequest request = AuthenticationRequest(
          email: fingerPrintInfo.cmpUserId,
          password: fingerPrintInfo.cmpCustpassword,
          channelCode: RequestConstants.channelCode,
          porOrgacode: RequestConstants.porOrgacode,
        );

        ServerResponse response = await repository.login(request);
        if (response.isError) {
          Toasty.error(response.errorMsg);
          return;
        }
        Get.toNamed(Routes.O_T_P_SCREEN, arguments: {
          AppConstants.SIGN_UP_FIRST_STEP_DATA: request,
          'loginUsingFingerPrint': loginUsingFingerPrint,

        });
        // showOtpInputDialog(context);
      }
    }, false);
  }
}
