// ignore_for_file: unnecessary_overrides

import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';
import 'package:IQ/app/global/login_snackbar.dart';
import 'package:IQ/app/global/snono_encrypt.dart';
import 'package:IQ/app/global/static_informs.dart';
import 'package:IQ/app/global/text_widget.dart';
import 'package:IQ/app/modules/service/api_service.dart';

class FillCardController extends GetxController with WidgetsBindingObserver {
  final formKey = GlobalKey<FormBuilderState>();

  String? secretNumber;
  bool inputsEntered = false;
  bool succeededFill = false;
  onChangeSecretNumberInput(secretNumberInput) {
    secretNumber = secretNumberInput;
    update();
  }

  Future redeemSecretNumber() async {
    if (secretNumber != null) {
      inputsEntered = true;
      update();
      if (!(formKey.currentState?.validate())!) {
        inputsEntered = true;
        update();
        return;
      }

      String payload = AES.encrypt(
        data: jsonEncode({"pin": "$secretNumber"}),
        passpharse: 'abcdefghijuklmno0123456789012345',
      );

      var value = await APIService.post('redeem', payload, true).timeout(
        const Duration(seconds: 10),
        onTimeout: () {
          inputsEntered = false;
          update();
          snack('autologin_failed_messageNull'.tr);
        },
      );
      if (value.runtimeType == int) {
        if (value == 0) {
          secretNumber = null;
          inputsEntered = false;
          update();

          snack('autologin_failed_message0'.tr);
        }
        if (value == -2) {
          secretNumber = null;
          inputsEntered = false;
          update();
          snack('autologin_failed_message'.tr);
        }
        if (value == 401) {
          secretNumber = null;
          inputsEntered = false;
          update();
          snack('autologin_failed_messageNull'.tr);
        }
        return;
      }

      var data = jsonDecode(value);
      debugPrint("value = $value");

      if (data["status"] == 200) {
        inputsEntered = false;
        succeededFill = true;
        secretNumber = null;
        update();
        FocusManager.instance.primaryFocus?.unfocus();
        return;
      } else {
        inputsEntered = false;
        succeededFill = false;
        secretNumber = null;
        update();
        FocusManager.instance.primaryFocus?.unfocus();
        Get.defaultDialog(
          title: '',
          titlePadding: const EdgeInsets.all(0),
          content: TextWidget(
            text: 'wrong_entered_card_secret_num_error'.tr,
            color: Colors.black,
            fontSize: 18,
          ),
          actions: [
            TextButton(
              onPressed: () {
                Get.back();
              },
              child: TextWidget(
                text: 'entered_card_secret_num'.tr,
                color: brandColor,
                fontSize: 20,
              ),
            )
          ],
        );
      }
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.inactive ||
        state == AppLifecycleState.detached ||
        state == AppLifecycleState.paused) return;
    if (state == AppLifecycleState.resumed) {
      defaultLocale = Platform.localeName.split('_')[0];
      textDirection =
          defaultLocale == "en" ? TextDirection.ltr : TextDirection.rtl;
      snackBarText = 'back_twice'.tr;
    }
  }

  @override
  void onInit() {
    WidgetsBinding.instance.addObserver(this);

    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this);
  }
}
