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 'package:gen_rentals/Utility/CustomSnackbar.dart';
import 'dart:io';

import '../Models/CommonResponse.dart';
import '../Models/ProfileResponse.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": androidInfo.data['user'].toString().trim(),
        "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 ?? "",
      };
    }else{
      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,
      ) async {
    try {
      _setLoggingOut(true);
      log("📡 Calling Logout API...");
      final response =
      await ApiCalling.logoutApi(accId, sessionId);

      _logoutResponse = response;
      _setLoggingOut(false);

      if (response != null && response.error == 0) {


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

        // Show toast/snackbar
        CustomSnackBar.showSuccess(
            context: context,
            message: response.message ?? "Logout successful"
        );

        // Navigate to login screen
        // Navigator.pushNamedAndRemoveUntil(context, '/login', (_) => false);
      } else {
        log("❌ Logout failed: ${response?.message}");
        CustomSnackBar.showError(
            context: context,
            message: response?.message ?? "Logout failed"
        );

      }
    } catch (e) {
      _setLoggingOut(false);
      log("🚨 Logout Error: $e");
      CustomSnackBar.showError(
          context: context,
          message: "Something went wrong: $e"
      );
    }
  }


  ProfileResponse? _profileData;
  ProfileResponse? get profileData => _profileData;

  /// Set loading state
  void setLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  ///  Fetch Profile Data
  Future<void> fetchProfile(BuildContext context, String accId, String sessionId) async {
    setLoading(true);
    try {
      final response = await ApiCalling.fetchProfileApi(accId, sessionId);

      if (response != null && response.error == "0") {
        _profileData = response;
        notifyListeners();
      } else {
        debugPrint("⚠️ Profile fetch failed: ${response?.message}");
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(response?.message ?? "Failed to fetch profile")),
        );
      }
    } catch (e) {
      debugPrint("❌ Profile fetch error: $e");
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("Error fetching profile")),
      );
    } finally {
      setLoading(false);
    }
  }


}


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;
  }

}




