import 'dart:io';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/HomeScreen.dart';
import 'package:generp/services/api_calling.dart';
import 'package:android_id/android_id.dart';
import 'package:device_info_plus/device_info_plus.dart';

import '../Utils/commonServices.dart';

class Loginnotifier extends ChangeNotifier {
  // Private variables
  String _emailError = '';
  String _passwordError = '';
  int _loginStatus = 0;
  bool _isLoading = false;
  int? _loginErrorCode;
  bool _pwdVisible = false;
  String _email = '';
  String _password = '';
  String _deviceDetails = "";
  String _deviceId = "";
  String _androidId = 'Unknown';
  static const _androidIdPlugin = AndroidId();
  bool get isButtonEnabled =>
      _email.isNotEmpty &&
      _password.isNotEmpty &&
      RegExp(r'\S+@\S+\.\S+').hasMatch(_email);

  // Public getters
  String get emailError => _emailError;
  String get passwordError => _passwordError;
  bool get isLoading => _isLoading;
  int? get loginErrorCode => _loginErrorCode;
  bool get pwdVisible => _pwdVisible;
  String get deviceId => _deviceId;
  String get deviceDetails => _deviceDetails;
  String get AndroidDevId => _androidId;
  int get loginStatus => _loginStatus;

  set isLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  Future<void> initAndroidId() async {
    String androidId;
    var deviceInfo = DeviceInfoPlugin(); // import 'dart:io'
    var androidDeviceInfo = await deviceInfo.androidInfo;
    _deviceDetails =
        "Version Name: " +
        androidDeviceInfo.version.baseOS.toString().trim() +
        ", " +
        "Version Code: " +
        androidDeviceInfo.version.codename.toString().trim() +
        ", " +
        "OS Version: " +
        androidDeviceInfo.version.codename.toString().trim() +
        ", SDK Version: " +
        androidDeviceInfo.version.sdkInt.toString().trim() +
        ", Device: " +
        androidDeviceInfo.device.toString().trim() +
        ", Model: " +
        androidDeviceInfo.model.toString().trim() +
        ", Product: " +
        androidDeviceInfo.product.toString().trim() +
        ", Manufacturer: " +
        androidDeviceInfo.manufacturer.toString().trim() +
        ", Brand: " +
        androidDeviceInfo.brand.toString().trim() +
        ", User: " +
        androidDeviceInfo.data['user'].toString().trim() +
        ", Display: " +
        androidDeviceInfo.display.toString().trim() +
        ", Hardware: " +
        androidDeviceInfo.hardware.toString().trim() +
        ", Board: " +
        androidDeviceInfo.board.toString().trim() +
        ", Host: " +
        androidDeviceInfo.host.toString().trim() +
        ", Serial: " +
        androidDeviceInfo.serialNumber.toString().trim() +
        ", ID: " +
        androidDeviceInfo.id.toString().trim() +
        ", Bootloader: " +
        androidDeviceInfo.bootloader.toString().trim() +
        ", CPU ABI1: " +
        androidDeviceInfo.supported64BitAbis.toString().trim() +
        ", CPU ABI2: " +
        androidDeviceInfo.supported64BitAbis.toString().trim() +
        ", FingerPrint: " +
        androidDeviceInfo.fingerprint.toString().trim();
    try {
      androidId = await _androidIdPlugin.getId() ?? 'Unknown ID';
      _deviceId = androidId;
      debugPrint("testing$deviceId");
      debugPrint(_deviceDetails.toString());
    } on PlatformException {
      androidId = 'Failed to get Android ID.';
    }
    _androidId = androidId;
    print(_deviceDetails);
    print(_deviceId);
    print(_androidId);
    notifyListeners();
  }

  Future<String?> getDevId() async {
    var deviceInfo = DeviceInfoPlugin(); // import 'dart:io'
    var iosDeviceInfo = await deviceInfo.iosInfo;
    _deviceId = iosDeviceInfo.identifierForVendor!;
    _deviceDetails = iosDeviceInfo.toString();
    notifyListeners();
    return null;
  }

  bool visibility_ov() {
    _pwdVisible = !_pwdVisible;
    print(_pwdVisible);
    notifyListeners();
    return _pwdVisible;
  }

  // Update methods for fields
  void updateEmail(String email) {
    _email = email;
    _emailError = '';
    notifyListeners();
  }

  void updatePassword(String password) {
    _password = password;
    _passwordError = '';
    notifyListeners();
  }

  // Validation
  bool _validate(String email, String password) {
    _emailError = '';
    _passwordError = '';

    if (!RegExp(r'\S+@\S+\.\S+').hasMatch(email)) {
      _emailError = "Please enter a valid email address";
    }

    if (password.isEmpty) {
      _passwordError = "Please enter your password";
    }
    _isLoading = false;
    notifyListeners();
    return _emailError.isEmpty && _passwordError.isEmpty;
  }

  Future<void> LoginApiFunction(context, email, password) async {
    try {
      if (!_validate(email, password)) return;

      _isLoading = true;
      notifyListeners();
      String? fcmToken = await FirebaseMessaging.instance.getToken();
      final data = await ApiCalling.LoginFunctionApi(
        email,
        password,
        fcmToken.toString() ?? "",
        deviceId.toString() ?? "",
        deviceDetails.toString(),
      );

      if (data != null) {
        _isLoading = false;
        _loginErrorCode = data.error;
        notifyListeners();

        debugPrint("${data.error} login error here");
        if (data.error == 0) {
          _loginStatus = 0;
          SharedpreferencesService().saveInt("loginStatus", 1);

          SharedpreferencesService().saveString("UserId", data.userId!);
          SharedpreferencesService().saveString("UserName", data.name!);
          SharedpreferencesService().saveString("UserEmail", data.emailId!);
          SharedpreferencesService().saveString("Session_id", data.sessionId!);
          var roles = data.permissions!.toString();
          SharedpreferencesService().saveString("roles", roles);

          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => MyHomePage(),
              settings: RouteSettings(name: "MyHomePage"),
            ),
          );
          notifyListeners();
        } else if (data.error == 1) {
          _isLoading = false;
          notifyListeners();
          toast(context, "You are not authorized to login in this device !");
        } else if (data.error == 2) {
          _isLoading = false;
          notifyListeners();
          toast(context, "Invalid login credentials !");
        } else {
          _isLoading = false;
          notifyListeners();
          toast(context, "Invalid login credentials !");
        }
      } else {
        _isLoading = false;
        notifyListeners();
      }
    } on Exception catch (e) {
      debugPrint("$e");
    }
  }
}
