import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../modules/profile/customer_request.dart';
import '../../repository/profile/request_repo.dart';

class CustomerRequestProvider with ChangeNotifier {
  final CustomerRequestRepository _repository = CustomerRequestRepository();
  bool isLoading = false;

  // List of fetched customer requests
  List<CustomerRequestStatusModel> requests = [];

  /// Create a new customer request
  Future<bool> sendRequest(String subject, String remarks) async {
    isLoading = true;
    notifyListeners();

    SharedPreferences prefs = await SharedPreferences.getInstance();
    int? customerId = prefs.getInt('customerId');

    if (customerId == null) {
      isLoading = false;
      notifyListeners();
      throw Exception("Something went wrong");
    }

    final model = CustomerRequestModel(
      referencedate: DateTime.now().toUtc().toIso8601String().split('.').first + 'Z',
      referencetype: "general", // always set default value
      customerid: customerId,
      tenantid: 0,
      locationid: 0,
      subject: subject,
      remarks: remarks,
      status: 0,
      apptypeid: 98,
    );

    final result = await _repository.createCustomerRequest(model);

    isLoading = false;
    notifyListeners();

    if (result != null && result is Map<String, dynamic> && result["status"] != false) {
      debugPrint("✅ API Success: $result");
      // Optionally refresh the list after creating a request
      await fetchCustomerRequests();
      return true;
    } else {
      debugPrint("❌ API Failed: $result");
      return false;
    }
  }

  /// Submit an account deletion request (reuses the same request pipeline
  /// used for support tickets, tagged so the backend/support team can
  /// identify and action it as a deletion instead of general support).
  Future<bool> sendAccountDeletionRequest() async {
    isLoading = true;
    notifyListeners();

    SharedPreferences prefs = await SharedPreferences.getInstance();
    int? customerId = prefs.getInt('customerId');

    if (customerId == null) {
      isLoading = false;
      notifyListeners();
      throw Exception("Something went wrong");
    }

    final model = CustomerRequestModel(
      referencedate: DateTime.now().toUtc().toIso8601String().split('.').first + 'Z',
      referencetype: "account_deletion",
      customerid: customerId,
      tenantid: 0,
      locationid: 0,
      subject: "Account Deletion Request",
      remarks: "Customer has requested deletion of their account and associated data.",
      status: 0,
      apptypeid: 98,
    );

    final result = await _repository.createCustomerRequest(model);

    isLoading = false;
    notifyListeners();

    if (result != null && result is Map<String, dynamic> && result["status"] != false) {
      debugPrint("✅ Account deletion request submitted: $result");
      return true;
    } else {
      debugPrint("❌ Account deletion request failed: $result");
      return false;
    }
  }

  /// Fetch customer requests (status)
  Future<void> fetchCustomerRequests({int pageNo = 1, int pageSize = 10}) async {
    isLoading = true;
    notifyListeners();

    SharedPreferences prefs = await SharedPreferences.getInstance();
    int? customerId = prefs.getInt('customerId');

    if (customerId == null) {
      isLoading = false;
      notifyListeners();
      return;
    }

    requests = await _repository.fetchCustomerRequests(
      customerId: customerId,
      pageNo: pageNo,
      pageSize: pageSize,
    );

    isLoading = false;
    notifyListeners();
  }
}
