import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:gen_rentals/Services/api_calling.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'dart:io';

import '../Models/CommonResponse.dart';

class RentalProvider extends ChangeNotifier {
  FetchMobileResponse? _response;
  FetchMobileResponse? otpResponse;
  bool _isLoading = false;


  FetchMobileResponse? get response => _response;
  bool get isLoading => _isLoading;
  bool isOtpLoading = false;

  //Fetch registered mobile number
  Future<void> fetchRentalMobile(String mob) async {
    _isLoading = true;
    notifyListeners();

    try {
      final result = await ApiCalling.fetchRentalMobileApi(mob);
      _response = result;
    } catch (e) {
      debugPrint("❌ Provider Error: $e");
      _response = null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // Fetch OTP for mobile
  Future<void> fetchMobileOtp(String mob, String otp) async {
    isOtpLoading = true;
    notifyListeners();

    try {
      final deviceDetails = await getDeviceDetails();
      final result = await ApiCalling.fetchMobileOtpApi(mob, otp, deviceDetails);
      otpResponse = result;
    } catch (e) {
      debugPrint("❌ OTP API Error: $e");
      otpResponse = null;
    } finally {
      isOtpLoading = false;
      notifyListeners();
    }
  }



  Future<Map<String, String>> getDeviceDetails() async {
    final deviceInfo = DeviceInfoPlugin();

    if (Platform.isAndroid) {
      final androidInfo = await deviceInfo.androidInfo;
      return {
        "versionName": androidInfo.version.release ?? "",
        "versionCode": androidInfo.version.codename ?? "",
        "osVersion": androidInfo.version.release ?? "",
        "sdkVersion": androidInfo.version.sdkInt.toString(),
        "device": androidInfo.device ?? "",
        "model": androidInfo.model ?? "",
        "product": androidInfo.product ?? "",
        "manufacturer": androidInfo.manufacturer ?? "",
        "brand": androidInfo.brand ?? "",
        "user": "",
        "display": androidInfo.display ?? "",
        "hardware": androidInfo.hardware ?? "",
        "board": androidInfo.board ?? "",
        "host": androidInfo.host ?? "",
        "serial": androidInfo.serialNumber ?? "unknown",
        "id": androidInfo.id ?? "",
        "bootloader": androidInfo.bootloader ?? "",
        "cpuAbi1": androidInfo.supportedAbis.isNotEmpty ? androidInfo.supportedAbis[0] : "",
        "cpuAbi2": androidInfo.supportedAbis.length > 1 ? androidInfo.supportedAbis[1] : "",
        "fingerprint": androidInfo.fingerprint ?? "",
      };
    }

    return {};
  }

  bool _isLoggingOut = false;
  bool get isLoggingOut => _isLoggingOut;

  CommonResponse? _logoutResponse;
  CommonResponse? get logoutResponse => _logoutResponse;

  /// 🔹 Set loading state
  void _setLoggingOut(bool value) {
    _isLoggingOut = value;
    notifyListeners();
  }

  /// 🔹 Call logout API
  Future<void> logout(
      BuildContext context,
      String accId,
      String sessionId,
      Map<String, String> deviceDetails,
      ) async {
    try {
      _setLoggingOut(true);
      log("📡 Calling Logout API...");
      final response =
      await ApiCalling.logoutApi(accId, sessionId, deviceDetails);

      _logoutResponse = response;
      _setLoggingOut(false);

      if (response != null && response.error == 0) {
        log("✅ Logout successful: ${response.message}");

        // Clear user data if needed
        // await SharedPrefHelper.clearAll();

        // Show toast/snackbar
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(response.message ?? "Logout successful"),
            backgroundColor: Colors.green,
          ),
        );

        // Navigate to login screen
        // Navigator.pushNamedAndRemoveUntil(context, '/login', (_) => false);
      } else {
        log("❌ Logout failed: ${response?.message}");
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(response?.message ?? "Logout failed"),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      _setLoggingOut(false);
      log("🚨 Logout Error: $e");
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Something went wrong: $e")),
      );
    }
  }


}


class FetchMobileResponse {
  String? error;
  String? errorMsg;
  String? accId;
  String? message;
  String? sessionId;

  FetchMobileResponse({this.error, this.errorMsg});

  FetchMobileResponse.fromJson(Map<String, dynamic> json) {
    error = json['error'];
    errorMsg = json['error_msg'];
    accId = json['acc_id'];
    message = json['message'];
    sessionId = json['session_id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['error'] = this.error;
    data['error_msg'] = this.errorMsg;
    data['acc_id'] = this.accId;
    data['message'] = this.message;
    data['session_id'] = this.sessionId;
    return data;
  }

}

