import 'dart:async';

import 'package:flutter/material.dart';
import 'package:rasadyar_auth/auth.dart';
import 'package:rasadyar_auth/data/common/dio_error_handler.dart';
import 'package:rasadyar_auth/data/models/request/login_request/login_request_model.dart';
import 'package:rasadyar_auth/data/models/response/auth/auth_response_model.dart';
import 'package:rasadyar_auth/data/models/response/user_info/user_info_model.dart';
import 'package:rasadyar_auth/data/models/response/user_profile_model/user_profile_model.dart';
import 'package:rasadyar_auth/data/repositories/auth_repository_imp.dart';
import 'package:rasadyar_auth/data/services/token_storage_service.dart';
import 'package:rasadyar_auth/data/utils/safe_call.dart';
import 'package:rasadyar_auth/presentation/widget/captcha/logic.dart';
import 'package:rasadyar_core/core.dart';

import '../../../data/models/local/user_local/user_local_model.dart';

enum AuthType { useAndPass, otp }

enum AuthStatus { init }

enum OtpStatus { init, sent, verified, reSend }

class AuthLogic extends GetxController {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  Rx<GlobalKey<FormState>> formKeyOtp = GlobalKey<FormState>().obs;
  Rx<GlobalKey<FormState>> formKeySentOtp = GlobalKey<FormState>().obs;
  Rx<TextEditingController> phoneNumberController = TextEditingController().obs;
  Rx<TextEditingController> passwordController = TextEditingController().obs;
  Rx<TextEditingController> phoneOtpNumberController =
      TextEditingController().obs;
  Rx<TextEditingController> otpCodeController = TextEditingController().obs;

  var captchaController = Get.find<CaptchaWidgetLogic>();

  RxnString phoneNumber = RxnString(null);
  RxBool isLoading = false.obs;
  RxBool isDisabled = true.obs;
  TokenStorageService tokenStorageService = Get.find<TokenStorageService>();

  Rx<AuthType> authType = AuthType.useAndPass.obs;
  Rx<AuthStatus> authStatus = AuthStatus.init.obs;
  Rx<OtpStatus> otpStatus = OtpStatus.init.obs;

  RxInt secondsRemaining = 120.obs;
  Timer? _timer;

  AuthRepositoryImpl authRepository = diAuth.get<AuthRepositoryImpl>();

  final Module _module = Get.arguments;

  void startTimer() {
    _timer?.cancel();
    secondsRemaining.value = 120;

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (secondsRemaining.value > 0) {
        secondsRemaining.value--;
      } else {
        timer.cancel();
      }
    });
  }

  void stopTimer() {
    _timer?.cancel();
  }

  String get timeFormatted {
    final minutes = secondsRemaining.value ~/ 60;
    final seconds = secondsRemaining.value % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

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

  @override
  void onReady() {
    super.onReady();
    iLog('module111 : ${_module.toString()}');
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

  bool _isFormValid() {
    final isCaptchaValid =
        captchaController.formKey.currentState?.validate() ?? false;
    final isFormValid = formKey.currentState?.validate() ?? false;
    return isCaptchaValid && isFormValid;
  }

  LoginRequestModel _buildLoginRequest() {
    final phone = phoneNumberController.value.text;
    final pass = passwordController.value.text;
    final code = captchaController.textController.value.text;
    final key = captchaController.captchaKey.value;

    return LoginRequestModel.createWithCaptcha(
      username: phone,
      password: pass,
      captchaCode: code,
      captchaKey: key!,
    );
  }

  /*Future<void> submitLoginForm() async {
    if (!_isFormValid()) return;
    iLog('module222 : ${_module.toString()}');
    final loginRequestModel = _buildLoginRequest();
    isLoading.value = true;
    await safeCall<AuthResponseModel?>(
      call: () => authRepository.login(authRequest: loginRequestModel.toJson()),
      onSuccess: (result) async {
        await tokenStorageService.saveModule(_module);
        await tokenStorageService.saveRefreshToken(result?.refresh ?? '');
        await tokenStorageService.saveAccessToken(result?.access ?? '');
      },
      onError: (error, stackTrace) {
        if (error is DioException) {
          diAuth.get<DioErrorHandler>().handle(error);
        }
        captchaController.getCaptcha();
      },
    );
    isLoading.value = false;
  }*/

  Future<void> submitLoginForm2() async {
    if (!_isFormValid()) return;
    AuthRepositoryImpl authTmp = diAuth.get<AuthRepositoryImpl>(instanceName: 'newUrl');
    isLoading.value = true;
    await safeCall<UserProfileModel?>(
      call: () => authTmp.login(
        authRequest: {
          "username": phoneNumberController.value.text,
          "password": passwordController.value.text,
        },
      ),
      onSuccess: (result) async {
        await tokenStorageService.saveModule(_module);
        await tokenStorageService.saveAccessToken(result?.accessToken ?? '');
        await tokenStorageService.saveRefreshToken(result?.accessToken ?? '');
      },
      onError: (error, stackTrace) {
        if (error is DioException) {
          diAuth.get<DioErrorHandler>().handle(error);
        }
        captchaController.getCaptcha();
      },
    );
    isLoading.value = false;
  }

  Future<void> getUserInfo(String value) async {
    isLoading.value = true;
    await safeCall<UserInfoModel?>(
      call: () async => await authRepository.getUserInfo(value),
      onSuccess: (result) async {
        if (result != null) {
          await newSetupAuthDI(result.backend ?? '');
          await tokenStorageService.saveApiKey(result.apiKey ?? '');
          await tokenStorageService.saveBaseUrl(result.backend ?? '');
        }
      },
      onError: (error, stackTrace) {
        if (error is DioException) {
          diAuth.get<DioErrorHandler>().handle(error);
        }
        captchaController.getCaptcha();
      },
    );
    isLoading.value = false;
  }

  GetSnackBar _errorSnackBar(String message) {
    return GetSnackBar(
      titleText: Text(
        'خطا',
        style: AppFonts.yekan14.copyWith(color: Colors.white),
      ),
      messageText: Text(
        message,
        style: AppFonts.yekan12.copyWith(color: Colors.white),
      ),
      backgroundColor: AppColor.error,
      margin: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      borderRadius: 12,
      duration: Duration(milliseconds: 3500),
      snackPosition: SnackPosition.TOP,
    );
  }
}
