import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/kyc_model.dart';
import 'kyc_service.dart';

class KycController extends GetxController {
  var kycList = <KycModel>[].obs; // Using an observable list to store KYC data
  var isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
   // loadKycFromLocalStorage(); // Load KYC data from local storage when initialized
  }

  Future<void> fetchKycData() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String? token = prefs.getString('token');
      isLoading(true);

      // Call the API to get KYC data
      var data = await KycService().getKycData(token!);

      if (data != null && data.isNotEmpty) {
        // Parse the list of KYC objects
        kycList.value = KycModel.fromJsonList(data); // Convert to List<KycModel>
       // saveKycToLocalStorage(); // Save the fetched KYC data to local storage
      } else {
        print("No KYC data found or API response is empty.");
      }

      print("KYC details: ${kycList[0].id}");
    } finally {
      isLoading(false);
    }
  }


  void approveKyc(String kycId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString('token');

    if (token != null && kycId.isNotEmpty) {
      print("Approving KYC with ID: $kycId");

      bool result = await KycService().approveKycStatus(token, kycId, "approved");

      if (result) {
        print("KYC approved successfully.");
      } else {
        print("Failed to approve KYC.");
      }
    } else {
      print("Token or KYC ID is missing.");
    }
  }

  // Update KYC status locally and persist the changes
  Future<void> updateKycStatus(KycModel kycModel, String status, String comment) async {
    final index = kycList.indexOf(kycModel);

    if (index != -1) {
      kycList[index].status = status; // Update status locally
     // saveKycToLocalStorage(); // Persist the changes locally

      // Show a success message after updating
      Get.snackbar(
        "Success",
        "KYC status updated to $status.",
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
    }
  }


  void rejectKyc(String kycId,String? rejectionReason,String? user) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString('token');
    //String? kycId = kycList[0].id; // Replace with the KYC ID
   // var rejectionReason = kycList[0].notes; // Example rejection reason
   // var principalDistributer = kycList[0].notes!.name;
    bool result = await  KycService().rejectKycStatus(token!, kycId, rejectionReason, user  , "reject");

    if (result) {
      print("KYC rejected successfully.");
    } else {
      print("Failed to reject KYC.");
    }
  }

}
