import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:digi_bank/src/app/constants/app_colors.dart';
import 'package:digi_bank/src/app/routes/routes.dart';
import 'package:digi_bank/src/common/model/user_model.dart';
import 'package:digi_bank/src/common/services/settings_service.dart';
import 'package:digi_bank/src/network/api/api_path.dart';
import 'package:digi_bank/src/network/response/status.dart';
import 'package:digi_bank/src/network/service/network_service.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class SignInController extends GetxController {
  final NetworkService _networkService = Get.find<NetworkService>();
  final RxBool isLoading = false.obs;
  final RxBool isPasswordVisible = true.obs;
  final RxBool isBiometricEnable = false.obs;
  final emailOrUsernameController = TextEditingController();
  final passwordController = TextEditingController();
  final Rx<UserModel> userModel = UserModel().obs;
  final RxString accountCreation = "".obs;
  final RxString biometricEmail = "".obs;
  final RxString biometricPassword = "".obs;

  Future<void> submitSignIn({bool useBiometric = false}) async {
    isLoading.value = true;
    final String email =
        useBiometric
            ? biometricEmail.trim()
            : emailOrUsernameController.text.trim();

    final String password =
        useBiometric
            ? biometricPassword.trim()
            : passwordController.text.trim();

    try {
      final response = await _networkService.login(
        email: email,
        password: password,
      );

      if (response.status == Status.completed) {
        await postFcmNotification(email: email, password: password);
      }
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> fetchUser({
    required String email,
    required String password,
  }) async {
    isLoading.value = true;
    try {
      final response = await _networkService.get(
        endpoint: ApiPath.userEndpoint,
      );
      if (response.status == Status.completed) {
        userModel.value = UserModel.fromJson(response.data!);

        if (userModel.value.twoFa == true) {
          Get.toNamed(BaseRoute.twoFa, arguments: {"email": email});
          resetFields();
        } else {
          await Get.find<SettingsService>().saveLoggedInUserEmail(email);
          await Get.find<SettingsService>().saveLoggedInUserPassword(password);

          Get.offAllNamed(BaseRoute.navigation);
          resetFields();
          _showToast("Login successful!", AppColors.success);
        }
      }
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> postFcmNotification({
    required String email,
    required String password,
  }) async {
    try {
      final deviceInfoPlugin = DeviceInfoPlugin();
      final savedFcmToken = await SettingsService.getFcmToken();
      String deviceId = '';
      String deviceType = '';

      if (Platform.isAndroid) {
        final androidInfo = await deviceInfoPlugin.androidInfo;
        deviceId = androidInfo.id;
        deviceType = 'android';
      } else if (Platform.isIOS) {
        final iosInfo = await deviceInfoPlugin.iosInfo;
        deviceId = iosInfo.identifierForVendor ?? '';
        deviceType = 'ios';
      } else {
        deviceType = 'unknown';
        deviceId = 'unknown';
      }

      final Map<String, String> requestBody = {
        'device_id': deviceId,
        'device_type': deviceType,
        'fcm_token': savedFcmToken ?? '',
      };

      final response = await _networkService.globalPost(
        endpoint: ApiPath.getSetupFcm,
        data: requestBody,
      );

      if (response.status == Status.completed) {
        await fetchUser(email: email, password: password);
      }
    } finally {}
  }

  void resetFields() {
    passwordController.clear();
    biometricEmail.value = "";
    biometricPassword.value = "";
  }

  void _showToast(String message, Color backgroundColor) {
    Fluttertoast.showToast(
      msg: message,
      backgroundColor: backgroundColor,
      toastLength: Toast.LENGTH_LONG,
      gravity: ToastGravity.BOTTOM,
    );
  }
}
